简体   繁体   English

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

[英]Dynamically change cell color in Excel

I'm using POI library to deal with the Excel file, I want to change the ForGroundColor of the particular cells. 我正在使用POI库来处理Excel文件,我想更改特定单元格的ForGroundColor。 As I'm not satisfied with the list of IndexedColors I want to create my own by substituting one already existing (in my case HSSFColor.BLUE), the problem is - it saves only the color from the last iteration (all cells have the same color). 由于我对IndexedColors列表不满意,我想通过替换一个已经存在的(在我的情况下是HSSFColor.BLUE)来创建我自己的,它的问题是 - 它只保存上一次迭代的颜色(所有单元都有相同的颜色)颜色)。

The code (convData - two dim double array, normalized to 255): 代码(convData - 两个昏暗的双数组,标准化为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);
            }
        }

Your problem is that you're creating one single cell style, assigning it to a bunch of cells, then changing it to be blue part way through. 你的问题是你正在创建一个单一的单元格样式,将它分配给一堆单元格,然后将其更改为蓝色部分。 As the cell style is global, that blue then applies to everything 由于单元格样式是全局的,因此蓝色适用于所有内容

Instead, you either need move the "redefine what blue is" outside of the loop, or create a new cell style + apply colour to it for each differently coloured cell. 相反,您需要在循环外部移动“重新定义蓝色是什么”,或者为每个不同颜色的单元格创建新的单元格样式+应用颜色。 However, there's a limit to the number of colours and cell styles you can have, so make sure you re-use them if you have multiple cells wanting the same colour 但是,您可以拥有的颜色和单元格样式数量有限制,因此如果您有多个想要相同颜色的单元格,请确保重复使用它们

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM