First you'll need to make sure to have a single string with '\n'
as a separator instead of the list:
df = pd.DataFrame([
['First Line\nSecond line'],
['First line\nsecond line\nthird line'],
['first line']
])
You can then call to_excel
like you normally do, then open the file with openpyxl and set the cells' .style.alignment.wrap_text
property to True
like the answer for this question suggests.
Alternatively you can wrap df
with a StyleFrame
object (full disclosure: I'm the author of this module, pip install styleframe
to get it) that does it for you (wrap_text=True
is used as default):
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()