Python: How to create multi line cells in excel when exporting a pandas dataframe

时间:2018-06-18 11:39:16

标签: python excel pandas

I have the following pandas Dataframe

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

I am trying to export it into an Excel file. However I would like that between each list-element a line break is entered, similar to ALT-ENTER in Excel. So at the end, the excel would look like this:

enter image description here

Thank you

1 个答案:

答案 0 :(得分:4)

首先,您需要确保将单个字符串'\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为你做的事情(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()