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

时间:2019-12-12 00:36:25

标签: python excel openpyxl conditional-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()

2 个答案:

答案 0 :(得分:0)

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

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

检查此链接: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()

结果:

enter image description here

答案 1 :(得分:0)

在@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