在java

时间:2017-10-18 15:28:41

标签: java apache-poi

我希望使用Java并使用Apache POI 3.11获得Excel单元格的颜色。我尝试过以下方法:

if (cell.getCellStyle().getFillForegroundColor() == HSSFColor.RED.index) {
}

在上面的代码块中,左侧表达式只返回64,我不确定原因。

我也试过这个:

Color color = cell.getCellStyle().getFillForegroundColorColor();

if (color != null) {
    if (color instanceof XSSFColor) {
        System.out.println("color is: " + ((XSSFColor) color).getARGBHex());
    } else if (color instanceof HSSFColor) {
        if ((color instanceof HSSFColor.AUTOMATIC))
            System.out.println("color is: " + ((HSSFColor) color).getHexString());
    }
}

但是,这也不起作用。

我将如何做到这一点?

1 个答案:

答案 0 :(得分:0)

对于HSSF(excel 97)格式,字体样式存储在工作簿中的数组中。要获取单元格的字体颜色,请从数组中检查应用字体索引的单元格样式,然后从工作簿字体数组中按索引获取字体,最后检查使用字体的颜色。

此外,HSSFColor已被删除,因此请使用IndexedColors。

HSSFWorkbook workbook;
Cell cell;
// TODO initialize workbook & cell properly

short fontIndex = cell.getCellStyle().getFontIndex();
Font font = workbook.getFontAt(fontIndex);
short fontColor = font.getColor();
if (fontColor != IndexedColors.RED.index) {
    // it's not red!!
}

// or in one line
short fontColor = workbook.getFontAt(cell.getCellStyle().getFontIndex()).getColor();