Java POI最后一次CellStyle覆盖以前的CellStyles

时间:2016-06-06 00:04:24

标签: java apache-poi

我使用Java中的Apache POI库构建Excel文件。我希望有多个不同颜色的单元格,所以我创建了一种方法来构建我需要的样式。然后,我正在调用此方法来应用我需要的样式。

不幸的是,最后一个前景色应用于应用了前景色样式的所有先前单元格。因此,当我在C列中创建灰色单元格时,我在A列中创建的黄色单元格显示为灰色。[已编辑]

谁能告诉我我在这里做错了什么?

这里的方法(对不起它的不雅)[编辑]:

private CellStyle getCellStyle(boolean isHeader, boolean isShaded, String color){
    CellStyle style = workbook.createCellStyle();
    Font font = workbook.createFont();

    if (isHeader) {
        style.setBorderBottom(CellStyle.BORDER_MEDIUM);
        style.setBorderLeft(CellStyle.BORDER_MEDIUM);
        style.setBorderRight(CellStyle.BORDER_MEDIUM);
        style.setBorderTop(CellStyle.BORDER_MEDIUM);

        style.setAlignment(CellStyle.ALIGN_CENTER);

        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        font.setFontHeightInPoints((short) 14);
    }

    if (isShaded) {
        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        if (color.equalsIgnoreCase("yellow"))
            style.setFillForegroundColor(HSSFColor.YELLOW.index);
        else if (color.equalsIgnoreCase("light grey"));
            style.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
    }

    style.setFont(font);

    return style;

}

这是一个我称之为[编辑]方法的部分。

private void createHeaderRow(Row row, String year, String tableName) {
    int rowNum = row.getRowNum();
    int colNum = 0;
    boolean isHeader = true;

    CellStyle boldStyle = getCellStyle(isHeader, false, "");
    CellStyle yellowStyle = getCellStyle(isHeader, true, "yellow");
    CellStyle lightGreyStyle = getCellStyle(isHeader, true, "light grey");

    Cell cell = row.createCell(colNum++);
    cell.setCellValue(year);
    cell.setCellStyle(yellowStyle);

    cell = row.createCell(colNum++);
    cell.setCellValue("Company");
    cell.setCellStyle(boldStyle);

    cell = row.createCell(colNum++);
    cell.setCellValue("Total");
    cell.setCellStyle(lightGreyStyle);
}

1 个答案:

答案 0 :(得分:1)

问题不在Poi中,请看这里:

 else if (color.equalsIgnoreCase("light grey")); // <--- HERE
        style.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);

您的else if没有做任何事情,每次都会调用style.setFillForegroundColor(..GREY..)

即使没有必要,也可以使用大括号作为条件。

FIFY:

if (isShaded) {
    style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    if (color.equalsIgnoreCase("yellow")){
        style.setFillForegroundColor(HSSFColor.YELLOW.index);
    }
    else if (color.equalsIgnoreCase("light grey")){
        style.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
    }
}

刚刚测试过此代码,似乎对我来说很好