如何获得单元格的背景颜色使用Apache poi?

我们如何获得XSSFCell background color 。 我试过使用XSSFCellStyle但没有运气。

 FileInputStream fis = new FileInputStream(fileName); XSSFWorkbook book = new XSSFWorkbook(fis); XSSFSheet sheet = book.getSheetAt(0); XSSFRow row = sheet.getRow(0); System.out.println(row.getCell(0).getCellStyle().getFillForegroundColor()); 

使用这些步骤,我无法获得Short型的背景颜色表示。

签出此url:

https://issues.apache.org/bugzilla/show_bug.cgi?id=45492

 Cell cell = row.getCell(1); CellStyle cellStyle = cell.getCellStyle(); System.out.println("color = " + getColorPattern(cellStyle.getFillForegroundColor())); private short[] getColorPattern(short colorIdx){ short[] triplet = null; HSSFColor color = palette.getColor(colorIdx); triplet = color.getTriplet(); System.out.println("color : " + triplet[0] +"," + triplet[1] + "," + triplet[2]); return triplet; } 

这将返回RGB代码,但不是确切的代码。 但与XLS自定义颜色select器中的实际颜色代码相比,其返回的颜色差不多相同。

尝试这个:

 row.getCell(0).getCellStyle().getFillForegroundColorColor().getARGBHex() 

注意Color使用了两次

我在斯卡拉工作,但它是一样的。 你的代码是正确的。

这是我的,看看你是否能find差异:

 val wb = new XSSFWorkbook(path) for (id <- 0.until(sheetTot)) { val sh = wb.getSheetAt(id) print(sh.rowIterator().next().cellIterator().next().getCellStyle().getFillBackgroundColor()) } 

在我的情况下,结果是64

以下是在斯卡拉,但它确实显示如何从对象模型中获取颜色。 我想从实际的rgb值中实例化一个java.awt.Color对象(这很有用,部分原因是因为当我停在断点处时,debugging器显示对象的实际颜色,部分是因为这是用于导出到具有与Excel无关)。 我忽略了颜色的alpha值,我的Scala可能有点天真。 我build议,如果这不适合你,你应该设置一个断点,并检查密切相关的方法调用的结果,如getFillBackgroundColorColor()

 val rgb: Array[Byte] = cell.getCellStyle.getFillForegroundColorColor.getRgb def toInt(b: Byte): Int = { if (b<0) 256+b else b } val rgbInts = rgb.map(toInt) val color = new Color(rgbInts(0),rgbInts(1),rgbInts(2))