设置背景自定义颜色不适用于Apache POI中的XSSF

我写了应该创build一个Excel文件(xlsx或xls)的代码,并为单元格设置一个自定义背景颜色。 在创buildxls文件时,背景色可以正常工作,但在xlsx的情况下,背景色不会设置为正确的颜色。

我的代码有什么问题?

public class PoiWriteExcelFile { static Workbook workbook; static Sheet worksheet; public static void main(String[] args) { try { String type = "xlsx"; //xls FileOutputStream fileOut = new FileOutputStream("D:\\poi-test." + type); switch (type) { case "xls": workbook = new HSSFWorkbook(); break; case "xlsx": workbook = new XSSFWorkbook(); break; } CellStyle cellStyle = workbook.createCellStyle(); switch (type) { case "xls": HSSFPalette palette = ((HSSFWorkbook) workbook).getCustomPalette(); palette.setColorAtIndex(HSSFColor.LAVENDER.index, (byte)128, (byte)0, (byte)128); HSSFColor hssfcolor = palette.getColor(HSSFColor.LAVENDER.index); cellStyle.setFillForegroundColor(hssfcolor.getIndex()); break; case "xlsx": XSSFColor color = new XSSFColor(new java.awt.Color(128, 0, 128)); cellStyle.setFillForegroundColor(color.getIndex()); break; } worksheet = workbook.createSheet("POI Worksheet"); Row row1 = worksheet.createRow((short) 0); Cell cellA1 = row1.createCell((short) 0); cellA1.setCellValue("Hello"); cellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND); cellA1.setCellStyle(cellStyle); workbook.write(fileOut); fileOut.flush(); fileOut.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } 

您正在尝试使用索引颜色,但使用HSSF的代码可以find索引的颜色,但不能用于XSSF部分。 有Color.getIndex()将返回零,这是黑色的。

在颜色上有一个方法isIndexed() ,你需要检查颜色是否是索引的,只有在POI-Color-object上使用getIndex()才有意义。

您可以通过不使用索引的颜色使其适用于XSSF,而是通过使用以下内容实现全彩色值:

 ((XSSFCellStyle)cellStyle).setFillForegroundColor(color); 

这样您设置实际的颜色和生成的工作簿将具有正确的背景。