4

I want to wrap the header text.

My code is as follows:

writer = pd.ExcelWriter(r'C:\data.xlsx', engine='xlsxwriter')
df.to_excel(writer, index = False, sheet_name='Sheet1')
workbook = writer.book
dformat = workbook.add_format({'text_wrap': True})
pd.io.formats.excel.header_style = None
worksheet = writer.sheets['Sheet1']
worksheet.set_row(0, None, dformat)
writer.save()

However, the first row, that is, the headers does not wrap.

How to solve it?

Furthermore, how to set a filter on a column, say, a filter of column value greater than 10?

Thank you.

1 Answer 1

3

When use pandas to write the header, pandas applies their own styling.

If you want to apply your own styling to the header, you can write the data and header separately.

# Write data

writer = pd.ExcelWriter(r'C:\data.xlsx', engine='xlsxwriter')
df.to_excel(writer, index=False, sheet_name='Sheet1', header=False, startrow=1)

# Write header

for colx, value in enumerate(df.columns.values):
    writer.sheets['Sheet1'].write(0, colx, value)

# Style header

header_format = workbook.add_format({'bold': True, 'text_wrap': True, 'align': 'center'})
writer.sheets['Sheet1'].set_row(0, 30, formats['text_wrap'])

Sign up to request clarification or add additional context in comments.

1 Comment

Doesn't seem quite right. For one, I think you forgot to define formats or meant to use header_format in the call to set_row() at the end. Weirdly, the row height is applied when I try to do this, but not the wrapping.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.