Home > OS >  xlsxwriter: conditional formatting - AttributeError: 'str' object has no attribute '_
xlsxwriter: conditional formatting - AttributeError: 'str' object has no attribute '_

Time:11-09

I am trying to apply conditional formatting to a column using xlsxwriter.

I keep getting AttributeError: 'str' object has no attribute '_get_dxf_index' using the following code:

import xlsxwriter

xlsx_file = REPORTS   "\\"   project   report_date   '_inventory_init.xlsx'
writer = pd.ExcelWriter(xlsx_file, engine='xlsxwriter')
wb = writer.book

df.to_excel(writer, sheet_name='Not Supported', startrow = 1, header=False, index=False)
ws = writer.sheets['Not Supported']
ws.conditional_format('G1:G1048576', {'type': 'cell',
                                       'criteria': '==',
                                       'value': 'FALSE',
                                       'format': 'Bad'})

(max_row, max_col) = df.shape

column_settings = [{'header': column} for column in df.columns]
ws.add_table(0,0,max_row,max_col-1,{'columns': column_settings,
                                     'style': 'Table Style Medium 8'})
ws.set_column(0, max_col-1,15)

Full error message below:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-124-b1f6e2d0bdf4> in <module>
     47 df.to_excel(writer, sheet_name='Not Supported', startrow = 1, header=False, index=False)
     48 ws = writer.sheets['Not Supported']
---> 49 ws.conditional_format('G1:G1048576', {'type': 'cell',
     50                                        'criteria': '==',
     51                                        'value': 'FALSE',

~\anaconda3\lib\site-packages\xlsxwriter\worksheet.py in cell_wrapper(self, *args, **kwargs)
     98             args = new_args
     99 
--> 100         return method(self, *args, **kwargs)
    101 
    102     return cell_wrapper

~\anaconda3\lib\site-packages\xlsxwriter\worksheet.py in conditional_format(self, first_row, first_col, last_row, last_col, options)
   2280         # Get the dxf format index.
   2281         if 'format' in options and options['format']:
-> 2282             options['format'] = options['format']._get_dxf_index()
   2283 
   2284         # Set the priority based on the order of adding.

AttributeError: 'str' object has no attribute '_get_dxf_index'

CodePudding user response:

From reading the docs, you need to pass format=[format object] instead of format=[str] as an option to ws.conditional_format.

For more info about how to create a format object, see the format docs.

For what it's worth: In a brief search, I wasn't able to find anything about using already-existing-in-Excel-template formatting; it looks like you'll need to create/define your own formatting.

  • Related