Skip to content
Advertisement

Apache POI – Conditional formatting – need to set different cell range for rule and formatting

I am trying to create an empty excel template using apache poi java. I need to add a rule – when column no. 3 is populated then columns from 7 to 12 need to be highlighted in some color (as a mandatory indicator for the user).

I could find below code which colors the cell when the condition is met on the same cell. But I want to color/format different cells when the condition is met on current cell.

`   XSSFSheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting();
    ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule(ComparisonOperator.GT, "5");

    PatternFormatting patternFmt = rule1.createPatternFormatting();
    patternFmt.setFillBackgroundColor(IndexedColors.YELLOW.index);

    sheetCF.addConditionalFormatting(addressList.getCellRangeAddresses(), rule1); //when rule1 is met, same cell is colored yellow

But I want is when rule1 is met, then color a different cell range.

Is this possible in poi and how ?

Advertisement

Answer

Excel provides conditional formatting rules based on formulas.

The formula =AND(ISNUMBER($C1), $C1>5) returns True if the value in $C1 is numeric and greater than 5. If this formula is applied to the range G1:L1000, then each cell in this range will be true if the value in column C of the corresponding row fulfills that contition. That is because column C is fixated using $C in the formula. But the row numbers are not fixated and so are relative.

Example using apache poi:

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import org.apache.poi.ss.util.CellRangeAddress;

import java.io.FileOutputStream;

public class ConditionalFormatting {

 public static void main(String[] args) throws Exception {
  Workbook workbook = new XSSFWorkbook();

  Sheet sheet = workbook.createSheet("new sheet");
  SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting();

  ConditionalFormattingRule rule = sheetCF.createConditionalFormattingRule("AND(ISNUMBER($C1), $C1>5)");
  PatternFormatting fill = rule.createPatternFormatting();
  fill.setFillBackgroundColor(IndexedColors.YELLOW.index);
  fill.setFillPattern(PatternFormatting.SOLID_FOREGROUND);

  ConditionalFormattingRule[] cfRules = new ConditionalFormattingRule[]{rule};

  CellRangeAddress[] regions = new CellRangeAddress[]{CellRangeAddress.valueOf("G1:L1000")};

  sheetCF.addConditionalFormatting(regions, cfRules);

  FileOutputStream out = new FileOutputStream("ConditionalFormatting.xlsx");
  workbook.write(out);
  out.close();
  workbook.close();

 }
}

Now if you put something in column C what is numeric and greater than 5, the cells in columns G:L will be filled yellow.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement