首页 > 解决方案 > 如何根据布尔值在单元格中显示交通灯图标?

问题描述

我需要在单元格中显示绿色交通灯 if valueistrue和红色交通灯valueis false

我阅读了几个文档,ConditionalFormattingRule但我不明白它是如何工作的......

算法希望

...
Cell cell = sheet.getRow(1).getCell(5)
if (value) {
    cell.setIcon(TRAFFIC_LIGHT_GREEN)
}
else {
    cell.setIcon(TRAFFIC_LIGHT_RED)
}
...

有人可以帮我理解吗?

提前致谢,

问候

标签: javaapache-poi

解决方案


默认情况下IconMultiStateFormatting具有以下阈值:

  1. 如果单元格值大于或等于范围内所有值的 67%,则为绿色。
  2. 如果单元格值低于但大于或等于该范围内所有值的 33%,则为黄色。
  3. 如果单元格值低于范围内所有值的 33%,则为红色。

如果您需要其他阈值,则必须更改该默认值。

以下代码设置以下阈值:

  1. 如果单元格值大于或等于 1,则为绿色。
  2. 如果单元格值低于但大于或等于 0,则为黄色。
  3. 如果单元格值低于 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();

 }
}

推荐阅读