简体   繁体   English

Pandas:使用多行格式将包含字符串的数据帧写入 xlsx

[英]Pandas: Write dataframe containing strings to xlsx with multiline format

df=pd.DataFrame(['abc\n123\n232','1\n2\n3\n4\n5\n6'])
df.to_csv('text.csv')

I would like to have in a single cell in the xlsx (Edited: not csv):我想在 xlsx 的单个单元格中(编辑:不是 csv):

abc
123
232

The desired output is A1 cell only being filled.所需的输出是填充 A1 单元格。

The dataframe has only 1 cell.数据框只有 1 个单元格。 But the above code would result in the xlsx (Edited: not csv) printing that 1 cell into multiple cells.但是上面的代码会导致 xlsx(编辑:不是 csv)将该 1 个单元格打印到多个单元格中。 Is there a way to format and write the xlsx (Edited: not csv) into multilines within each cell ?有没有办法将 xlsx(编辑:不是 csv)格式化和写入每个单元格内的多行

Edit: I shall clarify my problem.编辑:我会澄清我的问题。 There is nothing wrong with my dataframe definition.我的数据框定义没有任何问题。 I would like the "\\n" within the strings in each cell of the dataframe to become a line break within the xlsx (Edited: not csv) cell.我希望数据帧的每个单元格中的字符串中的“\\n”成为 xlsx(已编辑:不是 csv)单元格中的换行符。 this is another example.这是另一个例子。

df=pd.DataFrame(['abc\n123\n232','1\n2\n3\n4\n5\n6'])
df.to_csv('text.csv')

The desired output is A1 and A2 cells only being filled.所需的输出是填充 A1 和 A2 单元格。

Edit 2: Not in csv but xlsx .编辑 2:不在 csv 中,而是在xlsx 中

You can use .to_excel with index=False and header=False .您可以将.to_excelindex=Falseheader=False

df.to_excel('test.xlsx', index=False, header=False)

But you may need to turn on 'Wrap Text' by yourself.但是您可能需要自己打开“自动换行”。

why not use openpyxl for that it will work为什么不使用 openpyxl 因为它会起作用

from openpyxl import Workbook

workbook = Workbook()
worksheet = workbook.worksheets[0]
worksheet.title = "Sheet1"
worksheet.cell('A1').style.alignment.wrap_text = True
worksheet.cell('A1').value = "abc\n123\n232"
worksheet.cell('B1').value = "1\n2\n3\n4\n5\n6"
workbook.save('test.xlsx')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM