首页 > 解决方案 > 如何使用 apache poi 4.1.0 为不同的单元格设置不同的背景颜色

问题描述

我想用不同的颜色设置不同单元格的背景颜色。但它总是为工作表的整个列设置一种颜色。下面是我的代码片段:

    for (int i = 1; i < rowTotal; i++) { 
        info("Read row " + i);

        XSSFRow dataRow = getRowData(i);

        setRowNumber(i);

        try {
            // do something

            setCellData("Passed", getRowNumber(), getColumnNumber());

            backgroundStyle.setFillForegroundColor(IndexedColors.GREEN.getIndex());
            backgroundStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);                

            currentCell = dataRow.getCell(getColumnNumber());
            currentCell.setCellStyle(backgroundStyle);                
        } catch (Exception e) {
            setCellData("Failed", getRowNumber(), getColumnNumber());

            backgroundStyle.setFillForegroundColor(IndexedColors.RED.getIndex());
            backgroundStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);

            currentCell = dataRow.getCell(getColumnNumber());
            currentCell.setCellStyle(backgroundStyle);                
        }
    }

它有效,但所有单元格都是红色的。我希望“通过”单元格应该是绿色的,但通过的单元格也是红色的。

我错过了什么?

谢谢。

标签: javaexcelapache-poi

解决方案


CellStyle在 apache-poi 中不打算为不同的样式使用单个实例。
每个都CellStyle定义了一个可以应用于单元格的样式,而您需要为工作簿中的每种不同样式设置一个样式,因为样式是在工作簿级别定义的。它们应该被重用,这也适用于Fonts 中使用的 s CellStyles,它们也应该被唯一定义。工作簿可以处理或存储的样式有一个最大值,但我不知道它的确切值。

在您的使用示例中,建议在循环之前创建样式(至少,在您的真实代码中可能有更好的样式创建位置),然后应用单元格所需的样式:

// create one style for a green background
CellStyle greenBackgroundStyle = wb.createCellStyle();
greenBackgroundStyle.setFillForegroundColor(IndexedColors.GREEN.getIndex());
backgroundStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);

// and another one for a red background
CellStyle redBackgroundStyle = wb.createCellStyle();
redBackgroundStyle.setFillForegroundColor(IndexedColors.RED.getIndex());
redBackgroundStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);

// then start looping
for (int i = 1; i < rowTotal; i++) { 
    info("Read row " + i);

    XSSFRow dataRow = getRowData(i);
    setRowNumber(i);

    try {
        // do something
        setCellData("Passed", getRowNumber(), getColumnNumber());            
        currentCell = dataRow.getCell(getColumnNumber());
        // set the style with green background
        currentCell.setCellStyle(greenBackgroundStyle);                
    } catch (Exception e) {
        setCellData("Failed", getRowNumber(), getColumnNumber());
        currentCell = dataRow.getCell(getColumnNumber());
        // set the style with red background
        currentCell.setCellStyle(redBackgroundStyle);                
    }
}

推荐阅读