I have the following pandas Dataframe
df = pd.DataFrame([
[['First Line', 'Second line']],
[['First line', 'second line', 'third line']],
[['first line']]
])
I am trying to export it into an Excel file. However I would like that between each list-element a line break is entered, similar to ALT-ENTER
in Excel.
So at the end, the excel would look like this:
Thank you
Pandas to_excel() function has number of useful arguments to customize the excel file. For example, we can save the dataframe as excel file without index using “index=False” as additional argument. One of the common uses in excel file is naming the excel sheet.
Multiple DataFrame to Excel 1 Save as excel format a multi index column Pandas with diffrent level names in a long format 0 Put multiple dataframes into one sheet AND across separate sheets 0 Export data from MSSQL to Excel 'template' saving with a new name using Python
Write row names (index). Create some sample data frames using pandas.DataFrame function. Now, create a writer variable and specify the path in which you wish to store the excel file and the file name, inside the pandas excelwriter function. The output showing the excel file with different sheets got saved in the specified location.
How to insert a header multiple times in a pandas dataframe 1 xlsxwriter and pandas for reporting 0 Multiple DataFrame to Excel 1 Save as excel format a multi index column Pandas with diffrent level names in a long format 0 Put multiple dataframes into one sheet AND across separate sheets
First things in the process is to read or create dataframe that you want to add to the excel file. then read the excel file using pd.ExcelWriter ('exisitingfile.xlsx') and save the information in a variable in our case variable name is ‘writer’.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With