Java 从 Apache poi 获取 excel 单元格背景颜色
Java get the excel cell background color from Apache poi
我正在尝试使用 Apache POI 在 .xlsx 文件中获取单元格颜色信息。
方法 cellStyle.getFillBackgroundColor()
返回短。如何将 short 转换为 java.awt.Color
或任何其他格式 (XSSFColor
).
最终我想根据背景颜色存储单元格的值。
Workbook workbook = WorkbookFactory.create(new FileInputStream (new File(SAMPLE_XLSX_FILE_PATH)));
Sheet sheet = workbook.getSheetAt(0);
DataFormatter dataFormatter = new DataFormatter();
sheet.forEach(row -> {
row.forEach(cell -> {
String cellValue = dataFormatter.formatCellValue(cell);
CellStyle cellStyle = cell.getCellStyle();
System.out.println(cellStyle.getFillBackgroundColor());
//Color userColor = cellStyle.getFillBackgroundColor(); //ERROR
});
System.out.println();
});
我使用的是 3.6 版,我认为它不支持 getFillBackgroundColorColor()
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.6</version>
</dependency>
对于 .xlsx 电子表格,您可以调用 the getFillBackgroundColorColor
(2 "Color" words) 方法。它 returns 一个 org.apache.poi.ss.usermodel.Color
(不是一个非常有用的接口),XSSFColor
实现。然后你可以将它转换为 XSSFColor
.
XSSFColor = (XSSFColor) cellStyle.getFillBackgroundColorColor();
或者,对于 .xlxs 电子表格,您可以将 CellStyle
转换为 XSSFCellStyle
,并将 XSSFCellStyle
的 getFillBackgroundColorColor
方法转换为 returns XSSFColor
直接。它还有 getFillBackgroundXSSFColor
做同样的事情。
Get the background fill color.
Note - many cells are actually filled with a foreground fill, not a background fill - see getFillForegroundColor()
请注意,实心填充是作为前景色实现的,因此前景色可能正是您真正想要的。前景色有互补的方法,例如getFillForegroundColorColor
.
我正在尝试使用 Apache POI 在 .xlsx 文件中获取单元格颜色信息。
方法 cellStyle.getFillBackgroundColor()
返回短。如何将 short 转换为 java.awt.Color
或任何其他格式 (XSSFColor
).
最终我想根据背景颜色存储单元格的值。
Workbook workbook = WorkbookFactory.create(new FileInputStream (new File(SAMPLE_XLSX_FILE_PATH)));
Sheet sheet = workbook.getSheetAt(0);
DataFormatter dataFormatter = new DataFormatter();
sheet.forEach(row -> {
row.forEach(cell -> {
String cellValue = dataFormatter.formatCellValue(cell);
CellStyle cellStyle = cell.getCellStyle();
System.out.println(cellStyle.getFillBackgroundColor());
//Color userColor = cellStyle.getFillBackgroundColor(); //ERROR
});
System.out.println();
});
我使用的是 3.6 版,我认为它不支持 getFillBackgroundColorColor()
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.6</version>
</dependency>
对于 .xlsx 电子表格,您可以调用 the getFillBackgroundColorColor
(2 "Color" words) 方法。它 returns 一个 org.apache.poi.ss.usermodel.Color
(不是一个非常有用的接口),XSSFColor
实现。然后你可以将它转换为 XSSFColor
.
XSSFColor = (XSSFColor) cellStyle.getFillBackgroundColorColor();
或者,对于 .xlxs 电子表格,您可以将 CellStyle
转换为 XSSFCellStyle
,并将 XSSFCellStyle
的 getFillBackgroundColorColor
方法转换为 returns XSSFColor
直接。它还有 getFillBackgroundXSSFColor
做同样的事情。
Get the background fill color.
Note - many cells are actually filled with a foreground fill, not a background fill - see
getFillForegroundColor()
请注意,实心填充是作为前景色实现的,因此前景色可能正是您真正想要的。前景色有互补的方法,例如getFillForegroundColorColor
.