Python:导出 Pandas 数据框时如何在 Excel 中创建多行单元格

标签 python excel pandas

我有以下 Pandas 数据框

df = pd.DataFrame([
    [['First Line', 'Second line']],
    [['First line', 'second line', 'third line']],
    [['first line']]
])

我正在尝试将其导出到 Excel 文件中。但是我希望在每个列表元素之间输入一个换行符,类似于 Excel 中的 ALT-ENTER。 所以最后,excel 看起来像这样:

enter image description here

谢谢

最佳答案

首先,您需要确保有一个以 '\n' 作为分隔符的字符串,而不是列表:

df = pd.DataFrame([
        ['First Line\nSecond line'],
        ['First line\nsecond line\nthird line'],
        ['first line']
    ])

然后您可以像往常一样调用 to_excel,然后使用 openpyxl 打开文件并将单元格的 .style.alignment.wrap_text 属性设置为 True 喜欢 this question 的答案建议。

或者你可以用 StyleFrame 包装 df对象 (完全公开:我是这个模块的作者,pip install styleframe 来获取它) 为你做的(wrap_text=True 默认使用):

from styleframe import StyleFrame

df = pd.DataFrame([
        ['First Line\nSecond line'],
        ['First line\nsecond line\nthird line'],
        ['first line']
    ])

StyleFrame(df).to_excel('test.xlsx').save()

关于Python:导出 Pandas 数据框时如何在 Excel 中创建多行单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50908676/

相关文章:

python - 将 Dash 应用程序集成到 Flask : minimal example

python - 使用 openpyxl 将边框应用于范围内的所有单元格

c# - 从 ASP.NET 将数据导出为 Excel 文件

python - Pandas 数据框上的用户定义函数

python - 如何对 pandas 中具有 bool 数据类型的变量执行 .describe() 方法

用特定索引中的 numpy 数组的其他值替换特定值的 Pythonic 方法

python - splinter 的绘图形状

python - matplotlib 直方图图例字体系列更改

使用 R 中的 openxlsx 从 Excel 工作表中读取列

python - Pandas 字典向量化查找