我正在使用 Apache POI 5.2.3 创建 HSSFWorkbook,我希望设置单元格的背景颜色。我有十六进制代码颜色,但我找不到使用它的系统。我知道我会像这样使用“字符串代码的索引”:
getIndex(LIGHT_ORANGE)
但是我不能使用像
LIGHT_ORANGE
这样的字符串,我必须使用像 C0C0C0
这样的字符串,而且我无法在 XSSWorkbook 上迁移
对于
XSSF
答案就在这里:APACHE POI 4.1:从十六进制代码设置单元格背景颜色。
这显示了第一个问题的解决方案,即如何从十六进制字符串获取
byte
数组。
但是二进制Excel文件系统在如何存储颜色方面有很大不同。人们不能像
HSSFColor
那样简单地将新颜色存储为 XSSFColor
。相反,所有颜色都需要位于调色板中 HSSFPalette
并且只有有限的免费颜色插槽。因此,要获得自定义的HSSFColor
,人们要么需要在调色板中找到类似的颜色,要么需要覆盖调色板中现有的颜色。我建议在调色板中找到类似的颜色。
以下代码展示了如何做到这一点:
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.commons.codec.binary.Hex;
class CreateHSSFColorOrXSSFColor {
public static void main(String[] args) throws Exception {
try (
//Workbook workbook = new XSSFWorkbook(); FileOutputStream fileout = new FileOutputStream("./Excel.xlsx")
Workbook workbook = new HSSFWorkbook(); FileOutputStream fileout = new FileOutputStream("./Excel.xls")
) {
String rgbS = "C0C0C0";
byte[] rgbB = Hex.decodeHex(rgbS); // get byte array from hex string
CellStyle cellStyle = workbook.createCellStyle();
if (workbook instanceof XSSFWorkbook) {
XSSFColor color = new XSSFColor(rgbB, null);
((XSSFCellStyle)cellStyle).setFillForegroundColor(color);
} else if (workbook instanceof HSSFWorkbook) {
HSSFPalette palette = ((HSSFWorkbook)workbook).getCustomPalette();
HSSFColor color = null;
// either find similar color in palette
color = palette.findSimilarColor(rgbB[0], rgbB[1], rgbB[2]);
if (color == null) {
color = palette.addColor(rgbB[0], rgbB[1], rgbB[2]);
}
// or ovwerwrite a indexed color in palette
//palette.setColorAtIndex(IndexedColors.LIME.getIndex(), rgbB[0], rgbB[1], rgbB[2]);
//color = palette.getColor(IndexedColors.LIME.getIndex());
cellStyle.setFillForegroundColor(color.getIndex());
}
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
Sheet sheet = workbook.createSheet();
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("custom");
cell.setCellStyle(cellStyle);
workbook.write(fileout);
}
}
}
代码部分
// or ovwerwrite a indexed color in palette
//palette.setColorAtIndex(IndexedColors.LIME.getIndex(), rgbB[0], rgbB[1], rgbB[2]);
//color = palette.getColor(IndexedColors.LIME.getIndex());
已被注释掉。如果取消注释,现有调色板颜色 LIME 将被自定义颜色覆盖。当然,LIME 颜色也不是更容易达到。