没有背景单元格的 HSSFColor 返回错误的背景颜色



我在我的项目中使用apache poi 3.9。我正在尝试读取HSSF对象Excel单元格,并从中获取背景颜色

Workbook myWorkBook = WorkbookFactory.create(new File(filePath));
Sheet mySheet = myWorkBook.getSheetAt(0);
Row currentRow = null;
Iterator<Row> rowIterator = mySheet.iterator();
while (rowIterator.hasNext())
{
currentRow = (Row) rowIterator.next();
totalColumns = currentRow.getPhysicalNumberOfCells();
for (int column = 0; column < totalColumns; column++)
{
Cell cell = currentRow.getCell(column);
CellStyle cellStyle = cell.getCellStyle();
short colorIdx=cellStyle.getFillForegroundColor();
HSSFWorkbook workbook = (HSSFWorkbook)myWorkBook;
HSSFPalette palette = workbook.getCustomPalette();
HSSFColor color = palette.getColor(colorIdx);
short[] triplet = color.getTriplet();
System.out.println("Now Color :"+triplet[0]+"-"+triplet[1]+"-"+triplet[2]);
}
}

在上面的代码中,我正在尝试获取RGB颜色。在那个问题是一些单元格颜色没有背景(没有填充(,但color.getTriplet(( 返回 0,0,0,即黑色背景颜色。如何区分和获取原始背景颜色。

Excel单元格填充是图案填充。填充前景色是图案的颜色,填充背景色是图案后面的颜色。

所以只有当有填充图案时,颜色才有意义,否则就没有意义。通过获取填充图案而不是通过颜色来确定单元格是否被填充也是如此。

执行 CellStyle.getFillPattern,然后仅当 FillPatternType 未FillPatternType.NO_FILL时,才会填充单元格。

在当前apache poi版本中,您将执行以下操作:

...
CellStyle cellStyle = cell.getCellStyle();
FillPatternType patternType = cellStyle.getFillPattern();
if (patternType  != FillPatternType.NO_FILL) {
 short colorIdx = cellStyle.getFillForegroundColor();
 ...

在古代apache poi 3.9 CellStyle.getFillPattern返回一个short。所以它必须是:

...
CellStyle cellStyle = cell.getCellStyle();
short patternType = cellStyle.getFillPattern();
if (patternType  != 0) {
 short colorIdx = cellStyle.getFillForegroundColor();
 ...

最新更新