首页 > 解决方案 > 如何在openpyxl中删除ConditionalFormattingList

问题描述

谁为整个列创建条件格式,或删除旧的条件格式?

1.我想为一整列添加条件格式,但是失败了。

2.然后我改变'E:E'->'E2:E10',它起作用了。但 E:10 是动态的,可能会随着数据的增加而增加。可更改为 E:100。我没办法。

在 python 3.7 win10 pro openpyxl 2.6.3

#1.I want to add a conditional_formatting for a whole column,But failed.
redFill = PatternFill(start_color='EE1111', end_color='EE1111', fill_type='solid')
ws.conditional_formatting.add('E:E',
                              CellIsRule(operator='==',
                                         formula=['"Fail"'],
                                         stopIfTrue=False,
                                         fill=redFill)
                              )

#2.then I change the 'E:E'->'E2:E10',it workd.
#but the E:10 is dynamic, may increase with data. May change to E:100.
# i found no way .
for i in ws.conditional_formatting:
    print(i.cells.ranges[0].bounds)
    ##(5, 1, 5, 10)
    #print(i.key)
    # 如果是单独给E列的都删除重新建立
    #if the conditional_formatting only for E column ,if want to remve the old one.
    from openpyxl.utils import column_index_from_string
    if column_index_from_string("E")==i.cells.ranges[0].bounds[0] and column_index_from_string("E")==i.cells.ranges[0].bounds[2]:
        del ws.conditional_formatting[i.key]#failed
File "D:\Python37\lib\site-packages\openpyxl\formatting\formatting.py", line 75, in add
    cf = ConditionalFormatting(range_string)
  File "D:\Python37\lib\site-packages\openpyxl\formatting\formatting.py", line 33, in __init__
    self.sqref = sqref
  File "D:\Python37\lib\site-packages\openpyxl\descriptors\base.py", line 69, in __set__
    value = _convert(self.expected_type, value)
  File "D:\Python37\lib\site-packages\openpyxl\descriptors\base.py", line 59, in _convert
    raise TypeError('expected ' + str(expected_type))
TypeError: expected <class 'openpyxl.worksheet.cell_range.MultiCellRange'>
(5, 1, 5, 10)
Traceback (most recent call last):
  File "G:/MyPython/Studty/1.3处理excel-openpyxl/10单元格设置条件格式.py", line 40, in <module>
    print(i.key)
AttributeError: 'ConditionalFormatting' object has no attribute 'key'

标签: pythonopenpyxl

解决方案


推荐阅读