[英]How to update range of cells where Excel Conditional Formatting applies with openpyxl
I have an Excel Workbook for which I would like to update the Conditional Formatting by using openpyxl
.我有一个 Excel 工作簿,我想使用
openpyxl
更新条件格式。
The documentation of openpyxl
can be found here for Conditional Formatting: https://openpyxl.readthedocs.io/en/stable/formatting.html ... however it only indicates how to create Conditional Formatting and not remove / update it.可以在此处找到有关条件格式的
openpyxl
文档: https ://openpyxl.readthedocs.io/en/stable/formatting.html ...但是它仅指示如何创建条件格式而不是删除/更新它。
I am trying to extend the range of some rules: I have a rule on range A4:V4
and I want to update it to A4:V100
.我正在尝试扩展一些规则的范围:我有一个关于范围
A4:V4
的规则,我想将其更新为A4:V100
。
How can I do this update of range of Conditional Formatting with openpyxl
?如何使用
openpyxl
更新条件格式范围?
Thanks谢谢
The current (version 3.0.9) implementation of Conditional Formatting in openpyxl
is the following: openpyxl
中条件格式的当前(版本 3.0.9)实现如下:
OrderedDict
(a dictionary with an order)OrderedDict
(带有顺序的字典)中ConditionalFormatting
objects;ConditionalFormatting
对象; it has an attribute sqref
for the reference of range (a MultiCellRange
object that can be easily converted to a string that looks like A4:V4
)sqref
用于引用范围(一个MultiCellRange
对象,可以很容易地转换为看起来像A4:V4
的字符串)The documentation clearly indicate ws.conditional_formatting.add(<range>, <rule>)
to add a rule, but you can actually access and delete rules like you would with a regular dictionary:文档清楚地表明
ws.conditional_formatting.add(<range>, <rule>)
添加规则,但您实际上可以像使用常规字典一样访问和删除规则:
ws.conditional_formatting[<range>]
ws.conditional_formatting[<range>]
del ws.conditional_formatting[<range>]
del ws.conditional_formatting[<range>]
One way to update is to delete and add again (like it seems to work if you want to update the reference of a Table in openpyxl
by the way).更新的一种方法是删除并再次添加(如果您想顺便更新
openpyxl
中的表的引用,它似乎可以工作)。
Put together, that could look like this:放在一起,可能看起来像这样:
import re
from os import startfile
from openpyxl import load_workbook
wb = load_workbook(xlsx)
ws = wb["My Super Worksheet"]
range_cells = "A4:V4"
new_range = "A4:V100"
rules = ws.conditional_formatting[range_cells]
del ws.conditional_formatting[range_cells]
for rule in rules:
ws.conditional_formatting.add(new_range, rule)
wb.save()
Note that you can access all the range references for Conditional Formatting with following list comprehension:请注意,您可以使用以下列表理解访问条件格式的所有范围引用:
refs_conditional_formats = [str(c.sqref) for c in ws.conditional_formatting]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.