Java 在Excel中动态更改单元格颜色

Java 在Excel中动态更改单元格颜色,java,excel,apache-poi,Java,Excel,Apache Poi,我正在使用POI库处理Excel文件,我想更改特定单元格的颜色。由于我对IndexedColors列表不满意,我想通过替换一个已经存在的(在我的例子中是HSSFColor.BLUE)来创建自己的IndexedColors列表,问题是-它只保存上一次迭代的颜色(所有单元格都具有相同的颜色) 代码(convData-二维双数组,标准化为255): hssfpalete hssfpalete=excelFile.getCustomPalette(); CellStyle CellStyle=excel

我正在使用POI库处理Excel文件,我想更改特定单元格的颜色。由于我对IndexedColors列表不满意,我想通过替换一个已经存在的(在我的例子中是HSSFColor.BLUE)来创建自己的IndexedColors列表,问题是-它只保存上一次迭代的颜色(所有单元格都具有相同的颜色)

代码(convData-二维双数组,标准化为255):

hssfpalete hssfpalete=excelFile.getCustomPalette();
CellStyle CellStyle=excelFile.createCellStyle();
hssfpalete=excelFile.getCustomPalette();
cellStyle.setFillPattern(cellStyle.SOLID\u前景);

对于(int i=0;i您的问题是,您正在创建一个单一单元格样式,将其分配给一组单元格,然后将其部分更改为蓝色。由于单元格样式是全局的,因此蓝色将应用于所有单元格

相反,您需要将“重新定义蓝色是什么”移动到循环之外,或者创建一个新的单元格样式并为每个不同颜色的单元格应用颜色。但是,您可以使用的颜色和单元格样式的数量是有限的,因此,如果有多个单元格需要相同的颜色,请确保重复使用它们

     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);
            }
        }