Java如何从Apache poi获取Excel单元格的背景颜色

3

我正在尝试使用Apache POI获取.xlsx文件中单元格颜色信息。

cellStyle.getFillBackgroundColor()方法返回short类型。我该如何将short转换为java.awt.Color或其他格式(XSSFColor)。

最终,我想根据单元格的背景颜色存储其值。

 Workbook workbook = WorkbookFactory.create(new FileInputStream (new File(SAMPLE_XLSX_FILE_PATH)));
    Sheet sheet = workbook.getSheetAt(0);
    DataFormatter dataFormatter = new DataFormatter();
    sheet.forEach(row -> {
        row.forEach(cell -> {
            String cellValue = dataFormatter.formatCellValue(cell);
            CellStyle cellStyle = cell.getCellStyle();
            System.out.println(cellStyle.getFillBackgroundColor());
            //Color userColor = cellStyle.getFillBackgroundColor(); //ERROR 
        });
        System.out.println();
    });

我正在使用版本为3.6的软件,我认为该版本不支持getFillBackgroundColorColor()函数。

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.6</version>
</dependency>

1
你为什么使用3.6版本?那个版本是在2009年发布的。 - rgettman
生产环境中的遗留应用程序。在更改任何JAR版本之前需要进行大量测试。 - Manvi
1个回答

7

使用 .xlsx 电子表格,你可以调用 getFillBackgroundColorColor 方法(2个“颜色”单词)。它返回一个org.apache.poi.ss.usermodel.Color (不是很有用的接口),而这个接口被XSSFColor实现。然后你可以将其强制转换为XSSFColor

XSSFColor = (XSSFColor) cellStyle.getFillBackgroundColorColor();

另外,对于 .xlxs 电子表格,您可以将 CellStyle 转换为 XSSFCellStyleXSSFCellStylegetFillBackgroundColorColor 方法直接返回一个 XSSFColor。它也有一个 getFillBackgroundXSSFColor 方法,实现的功能与前者相同。

获取背景填充颜色。

注意 - 许多单元格实际上是用前景填充而不是背景填充的 - 参见 getFillForegroundColor()

请注意,实心填充是作为前景色实现的,因此前景色可能是您真正需要的。 对于前景色,还有互补的方法,例如 getFillForegroundColorColor


我该如何从XSSFColor对象中检索十六进制值或颜色代码(例如Hex:#E5FFCC)? - Manvi
对我来说这是解决方法:不是使用getFillBackgroundColorColor,而是使用getFillForegroundColorColor,因为单元格的背景色是其填充的前景色。 - Olivier Faucheux

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接