Home » excel » excel – text_wrap format gets ignored using worksheet formatting

excel – text_wrap format gets ignored using worksheet formatting

Posted by: admin May 14, 2020 Leave a comment

Questions:

Wrap text does not work for me. I tried the below code:

writer = pd.ExcelWriter(out_file_name, engine='xlsxwriter')
df_input.to_excel(writer, sheet_name='Inputs')
workbook  = writer.book
worksheet_input = writer.sheets['Inputs']
header_format = workbook.add_format({
        'bold': True,
        'text_wrap': True})

# Write the column headers with the defined format.
worksheet_input.set_row(1,45,header_format )

Here is the screenshot of my result

enter image description here

Wrap text does not work for me. I tried the below code:

writer = pd.ExcelWriter(out_file_name, engine='xlsxwriter')
df_input.to_excel(writer, sheet_name='Inputs')
workbook  = writer.book
worksheet_input = writer.sheets['Inputs']
header_format = workbook.add_format({
        'bold': True,
        'text_wrap': True})

# Write the column headers with the defined format.
worksheet_input.set_row(1,45,header_format )

Here is the screenshot of my result

enter image description here

Got the below error using @amanb’s solution/code
enter image description here

My dataframe looks something like below

enter image description here

How to&Answers:

According to the official documentation for Formatting of the Dataframe headers:

Pandas writes the dataframe header with a default cell format. Since it is a cell format it cannot be overridden using set_row(). If you wish to use your own format for the headings then the best approach is to turn off the automatic header from Pandas and write your own.

So, we turn off the automatic header from Pandas and write our own. The defined header_format should be applied to each column header in the df_input and written to the worksheet. The following is customized to your requirement and a similar example is shown in the official docs.

# Turn off the default header and skip one row to allow us to insert a
# user defined header.
df_input.to_excel(writer, sheet_name='Inputs', startrow=1, header=False)

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

# Add a header format.
header_format = workbook.add_format({
    'bold': True,
    'text_wrap': True})

# Write the column headers with the defined format.
for col_num, value in enumerate(df_input.columns.values):
    worksheet.write(0, col_num + 1, value, header_format)