我在我的项目中使用 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();
...
关于java - 没有背景单元格的 HSSFColor 返回错误的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55507156/