如何通过openpyxl清除整个工作簿的条件格式

问题描述 投票:0回答:2

我编写了一些代码来进行条件格式设置。但是,每当我运行代码时,单元格都会使用相同的条件格式写入一次。有没有办法清除现有的并写入新的。

我查看了官方文档https://openpyxl.readthedocs.io/en/stable/formatting.html 但里面没有明确的功能

excel python-3.x openpyxl
2个回答
5
投票

如果您只想清除特定工作表的格式,则只需创建一个新列表:

from openpyxl.formatting.formatting import ConditionalFormattingList
ws.conditional_formatting = ConditionalFormattingList()

0
投票

如果您只想从特定单元格/单元格范围中删除条件格式,那么, 按照以下步骤删除条件格式。

wb = load_workbook("excel_file_path.xlsx")
ws = wb["sheet1"]
red_color = 'ffc7ce'
red_color_font = '9c0103'
red_font = styles.Font(size=14, bold=True, color=red_color_font)
red_fill = styles.PatternFill(start_color=red_color, end_color=red_color, 
            fill_type='solid')
# to get all cf_rules 
cf_rl = list(ws.conditional_formatting._cf_rules)

#to get specific cell from list of formatting
l1 = [i for i in cf_rl if i.sqref == "F51"]

#to delete conditional formatting from specific cell
del ws.conditional_formatting._cf_rules[l1[0]]

wb.save("test.xlsx")
© www.soinside.com 2019 - 2024. All rights reserved.