如何在openpyxl中排除条件格式中的空白单元格?

2024-04-30 03:49:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我在openpyxl中使用条件格式,但是在排除空白单元格时遇到了麻烦。我有一个列,其中的数字是用CellisRule格式化的。我使用的代码如下。在

ws2.conditional_formatting.add('C3:C25',CellIsRule(operator='lessThan', formula=['85'], stopIfTrue=True, fill=redFill,font=whiteText))

ws2.conditional_formatting.add('C3:C25',CellIsRule(operator='greaterThan', formula=['89.99'], stopIfTrue=True, fill=greenFill))

ws2.conditional_formatting.add('C3:C25',CellIsRule(operator='between', formula=['85', '89.99'], stopIfTrue=True, fill=yellowFill))

我试图使用公式化规则,但不知道该如何使用。在

更新:

与其使用条件格式,不如使用for循环。在

^{pr2}$

Tags: addtrue格式条件filloperatorconditionalformatting
1条回答
网友
1楼 · 发布于 2024-04-30 03:49:36

如果使用公式,则应使用an expression类型规则。一般来说,最好是分别编写规则和样式:

from openpyxl import Workbook
from openpyxl.formatting.rule import Rule
from openpyxl.styles.differential import DifferentialStyle
from openpyxl.styles import Font, PatternFill

red_text = Font(color="9C0006")
red_fill = PatternFill(bgColor="FFC7CE")
dxf = DifferentialStyle(font=red_text, fill=red_fill)

r = Rule(type="expression", dxf=dxf)
r.formula = ["NOT(ISBLANK(A1))"]

wb = Workbook()
ws = wb.active

for v in range(10):
    ws.append([v])

ws['A4'] = None
ws.conditional_formatting.add("A1:A10".format(ws.max_row), r)
wb.save("sample.xlsx")

相关问题 更多 >