java - 无法从 .xlsx 单元格读取 RGB 数据

标签 java excel apache apache-poi

我有一个简单的 .xlsx 文件,其中包含不同颜色的单元格。我需要获取颜色并检查它们是红色、黄色还是绿色。

Excel 文件如下所示:

enter image description here

为此,我尝试编写如下代码:

// get Cell color for specificed cells
        CellStyle cellStyle = currentCell.getCellStyle();
        XSSFCellStyle xssfCellStyle = (XSSFCellStyle) cellStyle;
        XSSFColor color = xssfCellStyle.getFillBackgroundXSSFColor();

        // check for null - when there is no cell background color, it returns null
        if (null != color) {
            String rgb =  color.getCTColor().getDomNode().getAttributes().getNamedItem("rgb").getNodeValue();
        }

此代码会抛出 NullPointerException,因为这里 color.getCTColor().getDomNode().getAttributes().getNamedItem("rgb") == null

然后我研究了另一种方法,如下:

// get Cell color for specificed cells
        CellStyle cellStyle = currentCell.getCellStyle();
        XSSFCellStyle xssfCellStyle = (XSSFCellStyle) cellStyle;
        XSSFColor color = xssfCellStyle.getFillBackgroundXSSFColor();
        if (color != null) {
            cellObject.setBackgroundColor(color.getARGBHex());
            System.out.println("row: " + rowIndex + "col: " + colIndex + "color : " + color.getARGBHex());
        }

但是,在这种方法中,每个单元格中 color.getARGBHex() 的值为 null

编辑:我尝试了另一种更简单的方法,如下:

//get cell colors
        short style = currentCell.getCellStyle().getFillBackgroundColor();
        System.out.println("row:"+rowIndex+",col:"+colIndex+" color: "+style);

此代码返回每个单元格的值:64

编辑:根据阿克塞尔的建议,我尝试了以下代码:

short xssfColor = currentCell.getCellStyle().getFillForegroundColor();

但是,此代码对于白色单元格返回 64,对于非白色单元格返回 0。

有人可以在这方面提供帮助吗? 提前致谢!

最佳答案

感谢阿克塞尔的提示。根据他的提示,我解决了这个问题。

我使用这段代码来解决这个问题。

// get cell colors
        XSSFColor xssfColor = (XSSFColor) currentCell.getCellStyle().getFillForegroundColorColor();
        if (xssfColor != null)
            System.out.println("row:" + rowIndex + ",col:" + colIndex + " color: " + xssfColor.getARGBHex());

这清楚地区分了所有颜色。 getARGBHex() 返回 RGB 分量以及 Alpha 值。但是,从数据中提取 RGB 的字符串操作很容易

例如:

Red : FFFF0000(由getARGBMex()方法返回,因此RGB值为:FF0000)。

再次感谢阿克塞尔的帮助。

关于java - 无法从 .xlsx 单元格读取 RGB 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48541583/

相关文章:

java - AIR admob 问题 #3500 : The extension context does not have a method with the name cacheInterstitial

excel - 使用 VBScript 将 Excel View 更改为页面布局

php - 如何确保只有一个 PHP 脚本实例通过 Apache 运行?

java - clojure/scala 互操作?

java - Jersey - Moxy 在类属性中返回附加 json

java - Solr:根据标签流行度提升搜索结果

excel - Excel 中的 TIMEVALUE 转换大于 24 小时

Excel - 公式或宏,用于根据链接到另一个单元格的另一个单元格填充单元格

apache - Chrome 开发者工具网络请求报告响应时间过长

java - 通过传递大文本从 php 调用 java jar 的最佳/最快方法是什么?