[英]How to set different background colors for different cells using apache poi 4.1.0
我想用不同的顏色設置不同單元格的背景顏色。 但它總是為工作表的整個列設置一種顏色。 下面是我的代碼片段:
for (int i = 1; i < rowTotal; i++) {
info("Read row " + i);
XSSFRow dataRow = getRowData(i);
setRowNumber(i);
try {
// do something
setCellData("Passed", getRowNumber(), getColumnNumber());
backgroundStyle.setFillForegroundColor(IndexedColors.GREEN.getIndex());
backgroundStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
currentCell = dataRow.getCell(getColumnNumber());
currentCell.setCellStyle(backgroundStyle);
} catch (Exception e) {
setCellData("Failed", getRowNumber(), getColumnNumber());
backgroundStyle.setFillForegroundColor(IndexedColors.RED.getIndex());
backgroundStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
currentCell = dataRow.getCell(getColumnNumber());
currentCell.setCellStyle(backgroundStyle);
}
}
它有效,但所有單元格都是紅色的。 我希望“通過”單元格應該是綠色的,但通過的單元格也是紅色的。
我錯過了什么?
謝謝。
在 apache-poi 中不打算對不同的CellStyle
使用單個 CellStyle 實例。
每個CellStyle
定義了一種可以應用於單元格的樣式,而您需要為工作簿中的每種不同樣式設置一個樣式,因為 styles 是在工作簿級別定義的。 它們應該被重用,這也適用於CellStyles
中使用的Font
,它們也應該被唯一定義。 工作簿可以處理或存儲 styles 的最大值,但我不知道它的確切值。
在您的使用示例中,建議在循環之前創建 styles(至少,在您的實際代碼中可能有更好的樣式創建位置),然后應用單元格所需的位置:
// create one style for a green background
CellStyle greenBackgroundStyle = wb.createCellStyle();
greenBackgroundStyle.setFillForegroundColor(IndexedColors.GREEN.getIndex());
backgroundStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
// and another one for a red background
CellStyle redBackgroundStyle = wb.createCellStyle();
redBackgroundStyle.setFillForegroundColor(IndexedColors.RED.getIndex());
redBackgroundStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
// then start looping
for (int i = 1; i < rowTotal; i++) {
info("Read row " + i);
XSSFRow dataRow = getRowData(i);
setRowNumber(i);
try {
// do something
setCellData("Passed", getRowNumber(), getColumnNumber());
currentCell = dataRow.getCell(getColumnNumber());
// set the style with green background
currentCell.setCellStyle(greenBackgroundStyle);
} catch (Exception e) {
setCellData("Failed", getRowNumber(), getColumnNumber());
currentCell = dataRow.getCell(getColumnNumber());
// set the style with red background
currentCell.setCellStyle(redBackgroundStyle);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.