有条件地使用Apache POI着色行

时间:2014-03-21 15:52:36

标签: java excel apache-poi xlsx

我在Apache poi API工作, 我想有条件地为线条着色, 规则是5行后的交替颜色:1-5行红色, 线6-10蓝色,线11-15红色。等等。

这条规则:

 ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("MOD(ROW(),2)");

不同颜色的交替行。

我如何写我的规则?

2 个答案:

答案 0 :(得分:3)

你需要两个规则,一个用于红色,一个用于蓝色。从ROW()减1,使第11行变为10,第15行变为14,因此mod的结果小于5.此外,第10行变为9且mod大于或等于5,所以它会变成蓝色。该模式在10行后重复,因此mod操作数为10的原因。

ConditionalFormattingRule red = sheetCF.createConditionalFormattingRule(
    "MOD(ROW() - 1, 10) < 5");
FontFormatting ffRed = red.createFontFormatting();
ffRed.setFontColorIndex(IndexedColors.RED.index);

ConditionalFormattingRule blue = sheetCF.createConditionalFormattingRule(
    "MOD(ROW() - 1, 10) >= 5");
FontFormatting ffBlue = blue.createFontFormatting();
ffBlue.setFontColorIndex(IndexedColors.BLUE.index);

然后,您可以使用SheetConditionalFormatting对象,使用适当的CellRangeAddress将条件格式添加到工作表中。

有关详细信息,请参阅Quick Guide on Conditional Formatting

答案 1 :(得分:0)

在我看来,以下(或类似的内容,可能与(ROW()+1)(ROW()-1)而不是ROW())应该有效:

ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("MOD(ROW() / 5,2)");