Python:导出 DataFrame 时在 Excel 单元格中添加换行符
我有以下 df
,其中有新的line字符 \ n
data
,如下所示。
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
,但没有奏效。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您使用 xlsxwriter 作为 Excel 写入引擎,您可以向列添加文本换行格式,如下所示:
输出:
If you use xlsxwriter as the Excel writing engine you can add a text wrap format to the column like this:
Output:
将 \n 替换为 CHAR(10),如下所示:https://exceljet.net/formula/add-a-line-break-with-a-formula
Replace \n with
CHAR(10)
as per here: https://exceljet.net/formula/add-a-line-break-with-a-formula