Search code examples
pythonpandascsvxlsx

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):

abc
123
232

The desired output is A1 cell only being filled.

The dataframe has only 1 cell. But the above code would result in the xlsx (Edited: not csv) printing that 1 cell into multiple cells. Is there a way to format and write the xlsx (Edited: not csv) into multilines within each cell?

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. 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.

Edit 2: Not in csv but xlsx.


Solution

  • You can use .to_excel with index=False and header=False.

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

    But you may need to turn on 'Wrap Text' by yourself.