openpyxl导出xlsx时条件格式与图片丢失问题求助
问题:OpenPyXL添加的图片和条件格式在Excel文件中消失
我有一个用于解析大型CSV文件、做统计分析并生成xlsx文件的脚本,此前一直使用openpyxl模块添加条件格式和插入图片,一切正常。现在导出的文件中这两类内容完全消失——程序运行无报错,workbook对象中能正常生成并添加这些内容,但打开文件后仅能看到pandas自动为列和索引标签添加的条件格式。
已尝试以下操作但均无效:
- 降级/升级pandas(从1.3.3到最新版)、openpyxl(从3.0.5到3.1.1)、xlsxwriter的版本
- 保存前检查workbook和worksheet对象,数据符合预期,但内容似乎未被保存到文件中
- 交替使用
writer.save()和writer.close()方法,结果一致
添加图片的代码
这段代码已使用多年,此前均正常运行:
importedimage = openpyxl.drawing.image.Image(os.path.join(imgfolder_dir, element)) importedimage.anchor = column_indexer[int(str(ix).replace("_", "")) - 1] + "1" importedimage.width = 900 importedimage.height = 360 worksheet.add_image(importedimage)
添加条件格式的代码
toplimit和bottomlimit为单元格变色阈值,这段代码此前也一直正常:
REDTEXT = openpyxl.styles.Font(size=14, bold=False, color="9C0006") REDBLOCK = openpyxl.styles.PatternFill(start_color="FFC7CE", end_color="FFC7CE", fill_type="solid") # YELLOWTEXT = openpyxl.styles.Font(size=14, bold=False, color="9C6500") # YELLOWBLOCK = openpyxl.styles.PatternFill(start_color="FFEB9C", end_color="FFEB9C", fill_type="solid") GREENTEXT = openpyxl.styles.Font(size=14, bold=False, color="006100") GREENBLOCK = openpyxl.styles.PatternFill(start_color="C6EFCE", end_color="C6EFCE", fill_type="solid") GRAPHS.conditional_formatting.add(format_cell, cfRule=openpyxl.formatting.rule.CellIsRule(operator="greaterThanOrEqual", formula[toplimit], fill=REDBLOCK, font=REDTEXT)) GRAPHS.conditional_formatting.add(format_cell, cfRule=openpyxl.formatting.rule.CellIsRule(operator="lessThanOrEqual", formula=[bottomlimit], fill=REDBLOCK, font=REDTEXT)) GRAPHS.conditional_formatting.add(format_cell, cfRule=openpyxl.formatting.rule.CellIsRule(operator="lessThanOrEqual", formula=[toplimit], fill=GREENBLOCK, font=GREENTEXT)) GRAPHS.conditional_formatting.add(format_cell, cfRule=openpyxl.formatting.rule.CellIsRule(operator="greaterThanOrEqual", formula=[bottomlimit], fill=GREENBLOCK, font=GREENTEXT))
文件保存相关代码
所有内容添加完成后调用writer.close():
writer = ExcelWriter(filename, engine="openpyxl") writer.workbook = analysis_book writer.worksheets = dict((ws.title, ws) for ws in analysis_book.worksheets) base_worksheet = analysis_book.worksheets[0] worksheet_0 = analysis_book.worksheets[1] worksheet_1 = analysis_book.worksheets[2]
内容的提问来源于stack exchange,提问作者Terabyte
相关产品推荐
相关产品推荐

