3

I have the following df, where there are new line characters \n in column Data, as shown below.

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

While exporting this df to Excel, I want line breaks at \n. It should look like:

Excel

I sought some help from here, using xlsxwriter but didn't work out.

cph_sto
  • 7,189
  • 12
  • 42
  • 78

2 Answers2

2

If you use xlsxwriter as the Excel writing engine you can add a text wrap format to the column like this:

import pandas as pd

df = pd.DataFrame({'ID': ['111', '222', '222'],
                   'Data': ['Population\nDensity',
                            'Population\nDensity',
                            'Population\nDensity\nArea']})

# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('pandas_test.xlsx', engine='xlsxwriter')

# Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer, sheet_name='Sheet1', index=False)

# Get the xlsxwriter workbook and worksheet objects.
workbook  = writer.book
worksheet = writer.sheets['Sheet1']

# Add a text wrap format.
text_wrap_format = workbook.add_format({'text_wrap': True})

# Add the format to column 2 (zero-indexed) and adjust the width.
worksheet.set_column(1, 1, 15, text_wrap_format)

# Close the Pandas Excel writer and output the Excel file.
writer.close()

Output:

enter image description here

jmcnamara
  • 38,196
  • 6
  • 90
  • 108
0

Replace \n with CHAR(10) as per here: https://exceljet.net/formula/add-a-line-break-with-a-formula