【问题标题】:Pandas to_excel doesnt write line breaksPandas to_excel 不写换行符
【发布时间】:2019-12-10 09:45:47
【问题描述】:

我正在尝试读取 Excel 并将数据写入带有新列的新 Excel。

这是一个示例 Excel module:请忽略表格格式

+-------+------+------+
| Col1  | Col2 | Col3 |
+-------+------+------+
| Prod1 | "ABC |  100 |
           XYZ"         
| Prod2 | Test |  200 |
+-------+------+------+

我阅读了这个 excel 并在数据框中添加了一个新列:

df = pd.read_excel(module)
df["Status"] = ""

我在新列中添加一个值:

rowIndex = df.index[df['Col1'] == 'Prod1'].tolist()
df.loc[rowIndex, 'Status'] = 'Yes'

我将df 写在一个新的 Excel 中:

df.to_excel("output.xlsx", index = None, header=True)

但在新的 excel 数据中看起来像:

+-------+----------+------+-------+
| Col1  | Col2     | Col3 | Status|
+-------+----------+------+-------+
| Prod1 | "ABCXYZ" |  100 | Yes   |

| Prod2 | Test     |  200 |       |
+-------+----------+------+-------+

如您所见,"ABCXYZ" 位于一行中。我希望它像在旧的 excel 中一样位于多行中。在新的 Excel 中写入数据时,我可以对代码进行哪些更改以保留这种格式?

P.S:调试时我发现df 的值为"ABC\nXYZ",但它仍然写在一行中。

【问题讨论】:

  • 如果将 merge_cells 更改为 False 会发生什么。 df.to_excel("output.xlsx", index = None, header=True, merge_cells=False)
  • 调试的时候发现...是的,这是在 Excel 中格式化的问题。

标签: python excel python-3.x pandas dataframe


【解决方案1】:

我发现下面的 python 库帮助我实现了格式化:

from StyleFrame import StyleFrame, Styler, utils

StyleFrame(df, styler_obj=Styler(horizontal_alignment=utils.horizontal_alignments.left, font = utils.fonts.calibri)).to_excel("output4.xlsx", index = None, header=True).save()

【讨论】:

    猜你喜欢
    • 2021-01-10
    • 1970-01-01
    • 2017-09-13
    • 2015-05-12
    • 1970-01-01
    • 2018-10-25
    • 2019-01-05
    • 2016-11-21
    • 2020-09-14
    相关资源
    最近更新 更多