代码之家  ›  专栏  ›  技术社区  ›  Alex

如何在apache poi的新版本中为单个单元格设置Excel单元格前景色?

  •  0
  • Alex  · 技术社区  · 9 年前

    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>3.11</version>
    </dependency>
    

    我发现用于设置前景色的旧代码不再编译,但我的新代码也不起作用。下面的代码将红色设置为整个工作表的前景色,但我需要各种单元格颜色。单元格值设置正确。

    XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet sheet = workbook.createSheet("Calendar");
    
    for (int rowNum=0; rowNum<n; rowNum ++)
    {
        Row row = sheet.createRow(rowNum);
        for (int colNum = 0; colNum < m; colNum++) 
        {
            Cell cell = row.createCell(colNum);
            cell.setCellValue(grid[rowNum][colNum]);
            CellStyle cellStyle = cell.getCellStyle();
            cellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
    
            cellStyle.setFillForegroundColor(HSSFColor.WHITE.index);
            if (res[rowNum][colNum] == CellEnum.BUSY.getValue())
            {
                cell.setCellValue(res[rowNum][colNum] + "|" + grid[rowNum][colNum]);
                cellStyle.setFillForegroundColor(HSSFColor.RED.index);
            }
            if (res[rowNum][colNum] == CellEnum.Pass.getValue())
            {
                cell.setCellValue(res[rowNum][colNum] + "|" + grid[rowNum][colNum]);
                cellStyle.setFillForegroundColor(HSSFColor.YELLOW.index);
            }
        }
    }
    
    1 回复  |  直到 8 年前
        1
  •  0
  •   Alex    9 年前

    阿克塞尔·里希特的评论实际上给出了解决方案。因此,改进后的代码如下:

        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet("Calendar");
        CellStyle styleWhite = workbook.createCellStyle();
        styleWhite.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        styleWhite.setFillPattern(CellStyle.SOLID_FOREGROUND);
    
        CellStyle styleYellow = workbook.createCellStyle();
        styleYellow.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
        styleYellow.setFillPattern(CellStyle.SOLID_FOREGROUND);
    
        CellStyle styleRed = workbook.createCellStyle();
        styleRed.setFillForegroundColor(IndexedColors.RED.getIndex());
        styleRed.setFillPattern(CellStyle.SOLID_FOREGROUND);
    
        for (int rowNum = 0; rowNum < n; rowNum++) {
            Row row = sheet.createRow(rowNum);
            for (int colNum = 0; colNum < m; colNum++) {
                Cell cell = row.createCell(colNum);
                cell.setCellValue(grid[rowNum][colNum]);
                cell.setCellStyle(styleWhite);
                if (res[rowNum][colNum] == CellEnum.BUSY.getValue()) {
                    cell.setCellStyle(styleRed);
                } else if (res[rowNum][colNum] == CellEnum.Pass.getValue()) {
                    cell.setCellStyle(styleYellow);
                } else {
                    cell.setCellStyle(styleWhite);
                }
            }
        }
    
    推荐文章