java - 如何使用 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);
}
}
它有效,但所有单元格都是红色的。我希望“通过”单元格应该是绿色的,但通过的单元格也是红色的。
我错过了什么?
谢谢。
解决方案
CellStyle
在 apache-poi 中不打算为不同的样式使用单个实例。
每个都CellStyle
定义了一个可以应用于单元格的样式,而您需要为工作簿中的每种不同样式设置一个样式,因为样式是在工作簿级别定义的。它们应该被重用,这也适用于Font
s 中使用的 s CellStyles
,它们也应该被唯一定义。工作簿可以处理或存储的样式有一个最大值,但我不知道它的确切值。
在您的使用示例中,建议在循环之前创建样式(至少,在您的真实代码中可能有更好的样式创建位置),然后应用单元格所需的样式:
// 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);
}
}
推荐阅读
- jquery - Jquery 不能在 Angular 6 中工作错误:ENOENT:没有这样的文件或目录,打开 '...\node_modules\jquery\dist\jquery.min.js'
- apache-flink - Flink EMR 安装
- node.js - 并行运行多个节点任务
- javascript - 使用传播添加到对象中的所有值
- sparql - 清除命名图的最有效方法?
- php - XAMPP PDO Sqlite 目录
- swift - iPhone X - UICollectionViewController 自动布局
- python - 使用 python 和 pandas 回测交易策略 - 一次只识别一个未平仓头寸
- docker - 无法在 Artifactory 中登录 docker 注册表
- php - 如何在 PHP 中生成具有不同元素编号的多个数组中的所有项目组合