xlsxwriter: conditional formatting - AttributeError: 'str' object has no attribute '_get_dxf_index'

xlsxwriter: conditional formatting - AttributeError: 'str' object has no attribute '_get_dxf_index'

我正在尝试使用 xlsxwriter 将条件格式应用于列。

我使用以下代码不断收到 AttributeError: 'str' object has no attribute '_get_dxf_index'

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)

下面是完整的错误信息:

---------------------------------------------------------------------------
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'

从阅读 the docs 开始,您需要将 format=[format object] 而不是 format=[str] 作为选项传递给 ws.conditional_format

有关如何创建 format 对象的详细信息,请参阅 the format docs

它的价值: 在简短的搜索中,我找不到任何关于使用已经存在的 Excel 模板格式的信息;看来您需要 create/define 自己的格式。