You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用openpyxl设置Excel单元格颜色无效果,请求排查问题

OpenPyXL单元格填充颜色不生效的解决办法

你的代码中第四个填充样式fill_cell4缺少patternType='solid'参数,这是导致该单元格颜色不显示的核心原因。OpenPyXL要求明确指定填充模式为solid,才能让设置的前景色作为单元格填充色生效。

修正后的代码如下:

import openpyxl 
from openpyxl.styles import PatternFill

wb = openpyxl.load_workbook("123.xlsx")
ws = wb.active

fill_cell1 = PatternFill(patternType='solid', fgColor='FC2C03')
fill_cell2 = PatternFill(patternType='solid', fgColor='03FCF4') 
fill_cell3 = PatternFill(patternType='solid', fgColor='35FC03') 
fill_cell4 = PatternFill(patternType='solid', fgColor='FCBA03')  # 补充patternType参数

ws['B2'].fill = fill_cell1
ws['B3'].fill = fill_cell2
ws['B4'].fill = fill_cell3
ws['B5'].fill = fill_cell4

wb.save("123.xlsx")

额外说明:

  • 所有需要纯色填充的样式都必须指定patternType='solid',其他填充模式(如gray125)对应不同的填充效果,无法实现纯色覆盖单元格的需求。
  • 保存文件后建议关闭并重新打开Excel,避免缓存导致的显示异常。

内容的提问来源于stack exchange,提问作者OakleyLee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 08:27:37