[英]Exporting Pandas DataFrame cells directly to excel/csv (python)
[英]Python: How to create multi line cells in excel when exporting a pandas dataframe
首先,您需要確保有一個以'\\n'
作為分隔符而不是列表的字符串:
df = pd.DataFrame([
['First Line\nSecond line'],
['First line\nsecond line\nthird line'],
['first line']
])
然后,您可以像to_excel
一樣調用to_excel
,然后使用 openpyxl 打開文件並將單元格的.style.alignment.wrap_text
屬性設置為True
就像這個問題的答案所暗示的那樣。
或者,您可以使用StyleFrame
對象(完全披露:我是該模塊的作者, pip install 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()
這是使用 xlsxwriter 中的xlsxwriter
Format.set_text_wrap()
的解決方案:
df = pd.DataFrame([
['First Line\nSecond line'],
['First line\nsecond line\nthird line'],
['first line']
])
with pd.ExcelWriter('file.xlsx', engine="xlsxwriter") as writer:
writer.book.formats[0].set_text_wrap() # update global format with text wrap
df.to_excel(writer)
如今,您可能只使用 ExcelWriter 中的 set_text_wrap() 方法!
cell_format = workbook.add_format()
cell_format.set_text_wrap()
worksheet.write(0, 0, "Some long text to wrap in a cell", cell_format)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.