首页 > 解决方案 > xlsxwriter:条件格式 - AttributeError:“str”对象没有属性“_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'

标签: pythonpandasxlsxwriter

解决方案


通过阅读文档,您需要传递format=[format object]而不是format=[str]作为选项传递给ws.conditional_format.

有关如何创建format对象的更多信息,请参阅format文档

值得一提的是:在简短的搜索中,我找不到任何关于使用 Excel 模板中已经存在的格式的信息;看起来您需要创建/定义自己的格式。


推荐阅读