Is there a way to get the add_format to work in xlsxwriter when writing a styler object?

Question:

I am trying to write out a styled dataframe to Excel using the xlsxwriter engine. It does work, but when I try to apply an add_format to a column, it won’t apply that format to the cells I wrote from the styled dataframe, only to the remaining blank cells. What am I doing wrong?

Here’s the test code I wrote to test this:

test_df = pd.DataFrame([11, 22.0, '33', '44 words might make this line wrap'])
test_df = test_df.style

writer = pd.ExcelWriter('format_test.xlsx', engine='xlsxwriter')

test_df.to_excel(writer,sheet_name='sheet',index=False, header=False)

worksheet = writer.sheets['sheet']  # pull worksheet object
workbook  = writer.book
format1 = workbook.add_format({
    'bold': True,
    'text_wrap': True,
    'align' : 'right',
    'valign': 'center',
    'fg_color': '#D7E4BC',
    'border': 1})
worksheet.set_column('A:A',23,format1)
worksheet.set_default_row(50)

writer.save()

So if I comment out the second line with the .style applied, most of the formats (text wrap, etc.) work. But as soon as I execute the .style again, the formats are all gone.

Any ideas?

Asked By: autonopy

||

Answers:

I’ve been told by John McNamara, author of the xlsxwriter, that it doesn’t work for this engine. He recommended that I try the openpyxl engine.

Answered By: autonopy