如何在 openpyxl 条件格式中使用占位符?

How to use a placeholder with openpyxl conditional formatting?

我对 Python 还比较陌生,但玩了一会儿,还是摸不着头脑。

我有一个使用 Openpyxl 将 returns 数据导入电子表格的查询,我想对该电子表格进行条件格式化。如果我输入确切的行数,我可以做到这一点,但行数因查询而异,所以我试图将它设置为仅条件格式我拥有的行数,所以我需要一个占位符可以看到下面。我使用一个变量 num_of_rows 表示 returns 行数。我想说:

ws.conditional_formatting.add(('H3:H%d', CellIsRule(operator='lessThan', formula=['10'],
                               stopIfTrue=True, fill=red_fill)) % (num_of_rows,))

但是我得到这个错误:

ws.conditional_formatting.add(('H3:H%d',
CellIsRule(operator='lessThan', formula=['10'], stopIfTrue=True,
fill=red_fill)) % (15,))
TypeError: unsupported operand type(s) for %: 'tuple' and 'tuple'

即使我将 % 之后的 num_of_rows 变量更改为一个数字,比如 15,它 returns 同样的错误。我如何在这里使用占位符?

改用此代码

ws.conditional_formatting.add(('H3:H%d' % (num_of_rows,), CellIsRule(operator='lessThan', formula=['10'], stopIfTrue=True, fill=red_fill)))

原因是您必须在字符串后立即使用 % 运算符,但您却试图在 ws.conditional_formatting.add() 函数上使用它。