[英]Apache-POI : How to set background color of a cell when creating spreadsheet?
[英]How to set an Excel Cell foreground color for individual cells in the new version for apache-poi?
我正在使用新版本的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);
}
}
}
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);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.