![](/img/trans.png)
[英]Java- Apache POI XSSF - Custom RGB Cellbackground not working
[英]Setting background custom color not working for XSSF in Apache POI
我編寫了應創建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()
方法,您需要檢查該顏色是否為索引色,然后才可以在POI-Color-object上使用getIndex()
。
您可以不使用索引顏色,而可以使用以下方法使用全色值來使其適用於XSSF:
((XSSFCellStyle)cellStyle).setFillForegroundColor(color);
這樣,您可以設置實際的顏色,並且生成的工作簿將具有正確的背景。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.