xlsxwriter设置条件格式报错:'str'对象无'_get_dxf_index'属性
报错原因
conditional_format方法的format参数要求传入xlsxwriter的Format实例对象,你直接传入了字符串'Bad',字符串没有_get_dxf_index属性,因此触发属性错误。
同时代码里还存在一个隐藏问题:如果G列存储的是布尔值,value参数写'FALSE'只会匹配字符串类型的FALSE,无法匹配布尔类型的False,会导致条件格式不生效。
修复方案
- 先通过工作簿对象
wb创建对应「Bad」样式的格式对象 - 替换条件格式里的format参数为该格式对象
- 按需调整value参数的类型
修正后的代码片段
import xlsxwriter import pandas as pd xlsx_file = REPORTS + "\\" + project + report_date + '_inventory_init.xlsx' writer = pd.ExcelWriter(xlsx_file, engine='xlsxwriter') wb = writer.book # 新增:创建对应Excel内置Bad样式的Format对象,可自行调整样式参数 bad_format = wb.add_format({ 'bg_color': '#FFC7CE', 'font_color': '#9C0006' }) df.to_excel(writer, sheet_name='Not Supported', startrow = 1, header=False, index=False) ws = writer.sheets['Not Supported'] # 修改format参数为创建好的格式对象,布尔值匹配直接传False即可 ws.conditional_format('G1:G1048576', {'type': 'cell', 'criteria': '==', 'value': False, 'format': bad_format}) (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) # 记得调用save/close方法写入文件 writer.close()
内容的提问来源于stack exchange,提问作者EA Bubnoff
相关产品推荐
相关产品推荐

