我编写的代码应该创建一个 Excel 文件(xlsx 或 xls)并为单元格设置自定义背景颜色。创建 xls 文件时,背景颜色工作正常,但在 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 代码中找到了索引颜色,但没有找到 XSSF 部分的索引颜色。 Color.getIndex()
将返回零,即黑色。
有一个关于颜色的方法isIndexed()
,您需要检查颜色是否是索引颜色,只有这样才有意义使用getIndex()
POI 颜色对象。
您可以通过不使用索引颜色而使用完整颜色值来使其适用于 XSSF:
((XSSFCellStyle)cellStyle).setFillForegroundColor(color);
通过这种方式,您可以设置实际颜色,生成的工作簿将具有正确的背景。
关于java - 设置背景自定义颜色不适用于 Apache POI 中的 XSSF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34861987/