簡體   English   中英

Python:導出pandas時如何在excel中創建多行單元格dataframe

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

我有以下 pandas Dataframe

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

我正在嘗試將其導出到 Excel 文件中。 但是我希望在每個列表元素之間輸入一個換行符,類似於 Excel 中的ALT-ENTER 。所以最后,excel 看起來像這樣:

在此處輸入圖像描述

謝謝

首先,您需要確保有一個以'\\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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM