Pregunta

This is my piece of code , but the problem is the it does not highlight the particular duplicate value , it's highlighting all the values if it finds the duplicate value in the cell at A5 and A6 but if I do changes at other cell like at A8 and A10 it does not highlight in Red colour.

This is the code:

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);
¿Fue útil?

Solución

COUNTIF($A$5:$A$500,A5)>1 is only going to apply when cell A5 is matched somewhere else.

So I'd resolve this by having a separate conditional formatting rule for each cell. I'd generate this like this:

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;
}

Then replace your code with:

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);
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top