首页 > 解决方案 > Conditional_formatting 使用 openpyxl 查找重复值

问题描述

我正在尝试让一个类使用 openpyxl 突出显示 A 列中的任何重复值。

目前 A 列具有以下值:

A
A
B
C
A
C
A

最终结果将所有 A 和 C 的单元格都涂成红色。我下面的代码没有抛出任何错误,但是在运行后打开文件时,重复的单元格中没有任何颜色。

import openpyxl
from openpyxl import formatting, styles
from openpyxl.formatting import Rule 
   
class Duplicates():
    def __init__(self, wb2):
        self.wb2 = wb2
        ws2=self.wb2.active
        self.red_fill = styles.PatternFill(start_color ='ffc7ce', end_color = 'ffc7ce', fill_type = 'solid')
        dxf= styles.differential.DifferentialStyle(fill=self.red_fill)
        rule = Rule(type='duplicateValues',dxf=dxf,stopIfTrue = None)
        ws2.conditional_formatting.add('$A:$A',rule)
        self.wb2.save('testing.xlsx')

Duplicates(wb2)

任何帮助将非常感激。

标签: pythonpython-3.xopenpyxl

解决方案


试试这个代码,它对我有用

red_text = Font(color="9C0006")
red_fill = PatternFill(bgColor="FFC7CE")
dxf = DifferentialStyle(font=red_text, fill=red_fill)
rule = Rule(type="duplicateValues", text="highlight", dxf=dxf)
wsRes.conditional_formatting.add('B1:B10000', rule)

推荐阅读