繁体   English   中英

Apache POI-条件格式-需要为规则和格式设置不同的单元格范围

[英]Apache POI - Conditional formatting - need to set different cell range for rule and formatting

我正在尝试使用apache poi java创建一个空的excel模板。 我需要添加一条规则-当列号为。 填充3,然后需要用某种颜色突出显示从7到12的列(作为用户的强制性指示)。

我可以在下面的代码中找到在同一单元格上满足条件时为单元格着色的代码。 但是我想在当前单元格满足条件时为不同的单元格上色/格式化。

`   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

但是我想要的是当满足rule1时,然后为另一个单元格区域着色。

在poi中这可能吗?如何?

Excel提供基于公式的条件格式设置规则。

如果$C1值为数字且大于=AND(ISNUMBER($C1), $C1>5)公式=AND(ISNUMBER($C1), $C1>5)返回True 。如果将此公式应用于范围G1:L1000 ,则此范围中的每个单元格将如果相应行的C列中的值满足该条件,则为true。 这是因为列C是在公式中使用$C固定的。 但是行号不是固定的,因此是固定的。

使用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);

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

 }
}

现在,如果您在C列中放置数值大于5的数值,则G:L列中的单元格将填充为黄色。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM