openpyxl 条件格式 - 规则在 Excel 文件中但不在格式中

openpyxl conditional formatting - Rule is in Excel file but not the formatting

我的目标是创建一个 Excel 文件,并使用 openpyxl 使用条件格式根据它们的值更改某些单元格的背景颜色。

当我打开使用 Excel 创建的文件时,我可以看到规则存在,但该规则不包括要应用的格式(背景颜色设置为 none)。因此,单元格没有背景颜色,尽管与公式相关的单元格边框不可见,就像背景为白色时一样。 不知道是我写错了,还是openpyxl有什么问题。

这是一个 MWE:

from openpyxl import Workbook
from openpyxl.styles import PatternFill
from openpyxl.formatting.rule import CellIsRule

wb = Workbook()
ws = wb.active

ws['B2'] = -2
ws['B3'] = -1
ws['B4'] =  0
ws['C2'] = -1
ws['C3'] =  0
ws['C4'] =  1

fill = PatternFill(start_color='538DD5', fill_type='solid')
ws.conditional_formatting.add('B2:C4', CellIsRule(operator='lessThan', formula=[0], fill=fill))

wb.save('mwe.xlsx')
wb.close()

您需要像这样添加参数 end_color :

fill = PatternFill(start_color='538DD5',end_color='538DD5',fill_type='solid')

检查这个 link : https://openpyxl.readthedocs.io/en/stable/formatting.html

from openpyxl import Workbook
from openpyxl.styles import PatternFill
from openpyxl.formatting.rule import CellIsRule

wb = Workbook()
ws = wb.active

ws['B2'] = -2
ws['B3'] = -1
ws['B4'] =  0
ws['C2'] = -1
ws['C3'] =  0
ws['C4'] =  1

fill = PatternFill(start_color='538DD5',end_color='538DD5',fill_type='solid')
#print(fill)
ws.conditional_formatting.add('B2:C4', CellIsRule(operator='lessThan', formula=[0], fill=fill))
wb.save('mwe.xlsx')
wb.close()

结果:

根据@GiovaniSalazar 的回答,我做了更多测试。 用于颜色的参数(start_color、end_color、fgColor、bgColor)与条件格式和简单格式的行为不同(openpyxl 中的错误?)。

这是两者的比较。唯一适用于两种格式的是 start_color + end_color.

from openpyxl import Workbook
from openpyxl.styles import PatternFill
from openpyxl.formatting.rule import CellIsRule

wb = Workbook()
ws = wb.active

ws['C2'] = -4
ws['C3'] = -3
ws['C4'] = -2
ws['C5'] = -1
ws['D2'] =  4
ws['D3'] =  3
ws['D4'] =  2
ws['D5'] =  1


ws['C1'] = 'Cond. formatting'
ws['F1'] = 'Formatting'

ws['A2'] = 'start+end'
fill = PatternFill(start_color='538DD5', end_color='538DD5', fill_type='solid')
# OK
ws.conditional_formatting.add('C2:D2', CellIsRule(operator='lessThan', formula=[0], fill=fill))
# OK
ws['F2'].fill = fill


ws['A3'] = 'start'
fill = PatternFill(start_color='538DD5', fill_type='solid')
# Problem (white background)
ws.conditional_formatting.add('C3:D3', CellIsRule(operator='lessThan', formula=[0], fill=fill))
# OK
ws['F3'].fill = fill


ws['A4'] = 'fgColor'
fill = PatternFill(fgColor='538DD5', fill_type='solid')
# Problem (white background)
ws.conditional_formatting.add('C4:D4', CellIsRule(operator='lessThan', formula=[0], fill=fill))
# OK
ws['F4'].fill = fill


ws['A5'] = 'bgColor'
fill = PatternFill(bgColor='538DD5', fill_type='solid')
# OK
ws.conditional_formatting.add('C5:D5', CellIsRule(operator='lessThan', formula=[0], fill=fill))
# Problem (black background)
ws['F5'].fill = fill


wb.save('mwe.xlsx')
wb.close()

输出Excel文件:

Output Excel file