2017-07-31 58 views
0

我现在用的是新版本的POI - 3.11如何在apache-poi的新版本中为单个单元格设置Excel单元格前景色?

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

如果你'CellStyle cellStyle = cell.getCellStyle();'和'cell'是无需特殊风格的新创建的单元格,然后你会得到默认的单元格样式。如果你想让它成为默认的单元格样式,你必须**创建一个单元格样式。请参阅:https://poi.apache.org/spreadsheet/quick-guide.html#FillsAndFrills。 –

回答

0

Axel Richter的评论实际上给出了解决方案。因此,精代码如下:

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); 
      } 
     } 
    } 
相关问题