如何突出显示Excel工作表中的重复值

时间:2014-05-05 13:37:50

标签: java servlets apache-poi

这是我的一段代码,但问题是它没有突出显示特定的重复值,如果它在A5和A6的单元格中找到重复值,但是如果我在其他单元格中进行了更改,则突出显示所有值就像在A8和A10一样,它没有以红色突出显示。

这是代码:

HSSFSheetConditionalFormatting mycf = new_hire.getSheetConditionalFormatting();

HSSFConditionalFormattingRule rule = mycf.createConditionalFormattingRule("COUNTIF($A$5:$A$500,A5)>1");
HSSFFontFormatting mypattern = rule.createFontFormatting();   
mypattern.setFontStyle(false, true);    
mypattern.setFontColorIndex(IndexedColors.RED.getIndex());
CellRangeAddress[] range = { CellRangeAddress.valueOf("A5:A500") };
mycf.addConditionalFormatting(range,rule);

1 个答案:

答案 0 :(得分:0)

COUNTIF($A$5:$A$500,A5)>1仅在单元格A5与其他地方匹配时才适用。

所以我通过为每个单元格设置单独的条件格式规则来解决这个问题。我会这样生成:

private HSSFSheetConditionalFormattingRule highlightIfMatch(HSSFSheetConditionalFormatting mycf, String cellId) {
    HSSFConditionalFormattingRule rule = mycf.createConditionalFormattingRule("COUNTIF($A$5:$a$500,"+cellId+")>1");
    //Go on to set your FontFormatting here
    return rule;
}

然后用以下代码替换您的代码:

HSSFConditionalFormatting mycf = new_hire.getSheetConditionalFormatting();
for(int x=4; x<500; x++) {
    HSSFRow row = new_hire.getRow(x);
    if(null == row) {
        row = new_hire.createRow(x);
    }
    HSSFCell cell = row.getCell(0); // 0 for column A
    if(null == cell) {
        cell = row.createCell(0);
    }
    String cellId = "A"+(x+1);
    CellRangeAddress[] range = new CellRangeAddress(x, x, 0, 0); // 0 for column A
    HSSFConditionalFormattingRule rule = highlightIfMatch(mycf, cellId);
    range.addConditionalFormatting(range, rule);
}