java - 如何根据布尔值在单元格中显示交通灯图标?
问题描述
我需要在单元格中显示绿色交通灯 if value
istrue
和红色交通灯value
is false
。
我阅读了几个文档,ConditionalFormattingRule
但我不明白它是如何工作的......
算法希望
...
Cell cell = sheet.getRow(1).getCell(5)
if (value) {
cell.setIcon(TRAFFIC_LIGHT_GREEN)
}
else {
cell.setIcon(TRAFFIC_LIGHT_RED)
}
...
有人可以帮我理解吗?
提前致谢,
问候
解决方案
默认情况下IconMultiStateFormatting
具有以下阈值:
- 如果单元格值大于或等于范围内所有值的 67%,则为绿色。
- 如果单元格值低于但大于或等于该范围内所有值的 33%,则为黄色。
- 如果单元格值低于范围内所有值的 33%,则为红色。
如果您需要其他阈值,则必须更改该默认值。
以下代码设置以下阈值:
- 如果单元格值大于或等于 1,则为绿色。
- 如果单元格值低于但大于或等于 0,则为黄色。
- 如果单元格值低于 0,则为红色。
使用 current 完成示例apache poi 4.1.0
:
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import java.io.FileOutputStream;
class ConditionalFormattingIconSet {
public static void main(String[] args) throws Exception {
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet1");
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setAlignment(HorizontalAlignment.CENTER);
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
Cell cell = sheet.createRow(0).createCell(0);
cell.setCellValue(-1);
cell.setCellStyle(cellStyle);
SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting();
ConditionalFormattingRule rule = sheetCF.createConditionalFormattingRule(IconMultiStateFormatting.IconSet.GYR_3_TRAFFIC_LIGHTS);
//rule.getMultiStateFormatting().setIconOnly(true);
IconMultiStateFormatting iconMultiStateFormatting = rule.getMultiStateFormatting();
ConditionalFormattingThreshold[] thresholds = iconMultiStateFormatting.getThresholds();
if (thresholds.length == 3) {
for (int i = 0; i < 3; i++) {
ConditionalFormattingThreshold threshold = thresholds[i];
System.out.println(i + " : " + threshold.getRangeType()); // default
System.out.println(i + " : " + threshold.getValue()); // default
// changing the thresholds
if (i == 0) {
threshold.setValue(0d);
} else if (i == 1) {
threshold.setRangeType(ConditionalFormattingThreshold.RangeType.NUMBER);
threshold.setValue(0d);
} else if (i == 2) {
threshold.setRangeType(ConditionalFormattingThreshold.RangeType.NUMBER);
threshold.setValue(1d);
}
}
}
ConditionalFormattingRule [] cfRules = {rule};
CellRangeAddress[] regions = {CellRangeAddress.valueOf("A1:A1")};
sheetCF.addConditionalFormatting(regions, cfRules);
FileOutputStream fileOut = new FileOutputStream("ConditionalFormattingIconSet.xlsx");
workbook.write(fileOut);
fileOut.close();
}
}
推荐阅读
- .net-core - SecurityRequirementsOperationFilter 不起作用
- php - 在我的 Woocommerce 帐户订单表中显示产品描述
- c++ - Parallel Boost Graph Library 示例代码的奇怪行为
- jenkins-plugins - 删除/重命名测试的结果仍然出现在使用 Jenkins Allure 插件的 Allure 报告中
- ios - React Native - 是否有使用 Apple ID 登录的库?
- python-3.x - “如何修复”'不能给变量更多的值' Python3
- jquery - 我想要 WordPress 重力表单在提交前上传文件验证
- java - 将检查异常与 java.util.function.Predicate 一起使用
- google-chrome - Google Chrome 语音转文本 vs 防火墙
- selenium - Groovy、Selenium、Cucumber,添加 ChromeOptions 参数