如何从 excel 2007 获取条件格式信息?

How to get conditional formatting info from excel 2007?

我必须比较两个不同的 excel 文件,当 HSSFConditionalFormattingRule 方法工作正常时,我不断从 XSSFConditionalFormattingRule 方法获取 0 或空值。

这是 .xls 和 .xlsx 文件的结果(两者具有相同的条件格式)。

2. CONDITIONAL FORMATTING DIFFERENCES

FORMULA1: 
Sheet1(0) Rule 0 IS:  SHOULD BE: IF(INT(COUNT($C:$C)*13%)>0,LARGE($C:$C,INT(COUNT($C:$C)*13%)),MAX($C:$C))<=A1

BCOLOR: 
Sheet1(0) Rule 0 IS: 0 SHOULD BE: 20

UNDERLINE: 
Sheet1(0) Rule 0 IS: 0 SHOULD BE: 255
Sheet1(0) Rule 0 IS: 0 SHOULD BE: 255
Sheet1(0) Rule 1 IS: 0 SHOULD BE: 255

LCOLOR: 
Sheet1(0) Rule 0 IS: 0 SHOULD BE: 20

FOREGROUND: 
Sheet1(0) Rule 0 IS: 0 SHOULD BE: 64
Sheet1(0) Rule 0 IS: 0 SHOULD BE: 64
Sheet1(0) Rule 1 IS: 0 SHOULD BE: 64

TYPE: 
Sheet1(0) Rule 0 IS: 0 SHOULD BE: 2

ESCAPMENT TYPE: 
Sheet1(0) Rule 0 IS: 0 SHOULD BE: -1
Sheet1(0) Rule 0 IS: 0 SHOULD BE: -1
Sheet1(0) Rule 1 IS: 0 SHOULD BE: -1

TCOLOR: 
Sheet1(0) Rule 0 IS: 0 SHOULD BE: 20

BACKCOLOR: 
Sheet1(0) Rule 0 IS: 0 SHOULD BE: 45
Sheet1(0) Rule 0 IS: 0 SHOULD BE: 43
Sheet1(0) Rule 1 IS: 0 SHOULD BE: 43

FONT COLOR: 
Sheet1(0) Rule 0 IS: 0 SHOULD BE: 20
Sheet1(0) Rule 0 IS: 0 SHOULD BE: 60
Sheet1(0) Rule 1 IS: 0 SHOULD BE: 60

RCOLOR: 
Sheet1(0) Rule 0 IS: 0 SHOULD BE: 20

您有两个问题 - 第一,您使用的是 Apache POI 的旧副本,第二,您调用了错误的方法来获取颜色

目前,您调用 rule.getPatternFormatting().getFillBackgroundColor() will return the index of the colour, or 0 if the colour isn't indexed. Almost all conditional formatting colours in HSSF are indexed, very few in XSSF are. As such, for most XSSF files, if you ask for the indexed colour you'll just get 0. Instead, you need to call rule.getPatternFormatting().getFillBackgroundColorColor() 其中 returns 一个颜色对象。从那里,你可以得到描述颜色的十六进制字符串,索引与否

所以,您应该像这样更改代码

int colourIndex = rule.getPatternFormatting().getFillBackgroundColor();
System.out.println("Colour index is " + colourIndex);

改为:

Color colour = rule.getPatternFormatting().getFillBackgroundColorColor();
if (colour instanceof ExtendedColor) {
   System.out.println("Colour is " + ((ExtendedColor)colour).getARGBHex());
} else {
   System.out.println("Colour is " + ((HSSFColor)colour).getHexString());
}

更新后的代码正确地获取颜色对象,无论是否索引,然后允许您获取它的十六进制表示。

此外,如前所述,您的 Apache POI 版本对于其中的某些内容来说太旧了。您需要升级到至少 3.13 beta 1,或者理想情况下升级到 3.13 beta 2 / 自 2015-07-20 以来的每晚构建。