我正在使用poi的新版本 - 3.11
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.11</version>
</dependency>
我发现用于设置前景色的旧代码不再编译,但我的新代码也不起作用。下面的代码将Red设置为整个工作表的前景色,但我需要各种单元格颜色。单元格值设置正确。
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);
}
}
}
答案 0 :(得分: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);
}
}
}