HSSFColor,无背景单元格返回错误的背景色

时间:2019-04-04 02:54:51

标签: java apache-poi

我在我的项目中使用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,即黑色背景色。如何区分并获取原始背景色。

1 个答案:

答案 0 :(得分:2)

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();
 ...