我有一个简单的 .xlsx 文件,其中包含不同颜色的单元格。我需要获取颜色并检查它们是红色、黄色还是绿色。
Excel 文件如下所示:
为此,我尝试编写如下代码:
// 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/