gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 17:50:58 28 4
gpt4 key购买 nike

我正在尝试使用 apache poi java 创建一个空的 Excel 模板。我需要添加一条规则 - 当列号为 1 时。填充 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

但我想要的是当满足规则1时,然后为不同的单元格区域着色。

这在 poi 中可能吗?如何实现?

最佳答案

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

如果 $C1 中的值为数字,则公式 =AND(ISNUMBER($C1), $C1>5) 返回 True并且大于 5。如果将此公式应用于范围 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);

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

}
}

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

关于java - Apache POI - 条件格式 - 需要为规则和格式设置不同的单元格范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50175877/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com