在Excel中dynamic更改单元格颜色

我正在使用POI库来处理Excel文件,我想要更改特定单元格的ForGroundColor。 由于我不满意IndexedColors的列表,我想通过replace一个已经存在的(在我的情况下为HSSFColor.BLUE)来创build自己的问题,它只保存最后一次迭代的颜色(所有单元格都相同颜色)。

代码(convData – 两个dim双数组,标准化为255):

HSSFPalette hssfPalette = excelFile.getCustomPalette(); CellStyle cellStyle = excelFile.createCellStyle(); hssfPalette = excelFile.getCustomPalette(); cellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND); for (int i=0; i<convData.length; i++) { Row row = excelSheet.createRow(i); for (int j=0; j<convData[i].length; j++) { Cell cell = row.createCell(j); hssfPalette.setColorAtIndex(HSSFColor.BLUE.index, convData[i][j].byteValue(), convData[i][j].byteValue(), convData[i][j].byteValue()); cellStyle.setFillForegroundColor(hssfPalette.getColor(HSSFColor.BLUE.index).getIndex()); cell.setCellStyle(cellStyle); } } 

你的问题是你正在创build一个单元格样式,将其分配给一堆单元格,然后将其更改为蓝色部分。 由于细胞风格是全球性的,那么蓝色就适用于一切

相反,您可能需要在循环外移动“重新定义蓝色”,或者为每个不同颜色的单元格创build新的单元格样式+应用颜色。 但是,颜色和单元格样式的数量是有限制的,所以如果您有多个单元格需要相同的颜色,请确保重新使用它们