POI 提供 HSSFColor 枚舉常見顏色索引。
HSSFCellStyle style = workbook.createCellStyle();
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style.setFillForegroundColor(HSSFColor.SKY_BLUE.index); // 使用索引
cell.setCellStyle(style);
將十六進制顏色字符串(如 "CBFDEE")解析為 RGB,註冊到調色盤自定義索引處。
String color = "CBFDEE";
int r = Integer.parseInt(color.substring(0,2), 16);
int g = Integer.parseInt(color.substring(2,4), 16);
int b = Integer.parseInt(color.substring(4,6), 16);
HSSFPalette palette = workbook.getCustomPalette();
palette.setColorAtIndex((short)9, (byte)r, (byte)g, (byte)b); // 索引 9
HSSFCellStyle style = workbook.createCellStyle();
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style.setFillForegroundColor((short)9); // 使用自定義索引
cell.setCellStyle(style);
HSSFWorkbook 僅支持 .xls;.xlsx 需用 XSSFWorkbook,API 類似但顏色處理不同(XSSFColor)。