Python:在导出 DataFrame 时将换行符添加到 Excel 个单元格中

Python: Add Line breaks into Excel cells while exporting the DataFrame

我有以下df,其中第Data列有换行符\n,如下图

import pandas as pd
import xlsxwriter
df = pd.DataFrame({'ID': ['111', '222', '222'],
                   'Data': ['Population\nDensity','Population\nDensity','Population\nDensity\nArea']})
print(df)

    ID  Data
0   111 Population\nDensity
1   222 Population\nDensity
2   222 Population\nDensity\nArea

在将此 df 导出到 Excel 时,我希望在 \n 处换行。它应该看起来像:

我使用 xlsxwriter 寻求帮助,但没有成功。

根据此处将 \n 替换为 CHAR(10)https://exceljet.net/formula/add-a-line-break-with-a-formula

如果您使用 xlsxwriter 作为 Excel 写作引擎,您可以像这样向列中添加文本换行格式:

import pandas as pd

df = pd.DataFrame({'ID': ['111', '222', '222'],
                   'Data': ['Population\nDensity',
                            'Population\nDensity',
                            'Population\nDensity\nArea']})

# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('pandas_test.xlsx', engine='xlsxwriter')

# Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer, sheet_name='Sheet1', index=False)

# Get the xlsxwriter workbook and worksheet objects.
workbook  = writer.book
worksheet = writer.sheets['Sheet1']

# Add a text wrap format.
text_wrap_format = workbook.add_format({'text_wrap': True})

# Add the format to column 2 (zero-indexed) and adjust the width.
worksheet.set_column(1, 1, 15, text_wrap_format)

# Close the Pandas Excel writer and output the Excel file.
writer.save()

输出: