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:
Thank you
答案 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()