Spire.XLS for Java支持为Excel设置三色及四色交通灯。该文将介绍如何在Excel工作表中设置三色交通灯。
import com.spire.xls.*;
import com.spire.xls.core.IConditionalFormat;
import com.spire.xls.core.spreadsheet.collections.XlsConditionalFormats;
import java.awt.*;
public class setTrafficLightsIcons {
public static void main(String[] args) {
//新建实例
Workbook workbook = new Workbook();
//添加工作表(默认3个)
Worksheet sheet = workbook.getWorksheets().get(0);
//添加数据并设置样式
sheet.getCellRange("A1").setText("Traffic Lights");
sheet.getCellRange("A2").setNumberValue(0.95);
sheet.getCellRange("A2").setNumberFormat("0%");
sheet.getCellRange("A3").setNumberValue(0.5);
sheet.getCellRange("A3").setNumberFormat("0%");
sheet.getCellRange("A4").setNumberValue(0.1);
sheet.getCellRange("A4").setNumberFormat("0%");
sheet.getCellRange("A5").setNumberValue(0.9);
sheet.getCellRange("A5").setNumberFormat("0%");
sheet.getCellRange("A6").setNumberValue(0.7);
sheet.getCellRange("A6").setNumberFormat("0%");
sheet.getCellRange("A7").setNumberValue(0.6);
sheet.getCellRange("A7").setNumberFormat("0%");
//设置高度和宽度
sheet.getAllocatedRange().setRowHeight(20);
sheet.getAllocatedRange().setColumnWidth(25);
//添加条件格式
XlsConditionalFormats conditional = sheet.getConditionalFormats().add();
conditional.addRange(sheet.getAllocatedRange());
IConditionalFormat format1 = conditional.addCondition();
//设置背景色
format1.setFormatType(ConditionalFormatType.CellValue);
format1.setFirstFormula("300");
format1.setOperator(ComparisonOperatorType.Less);
format1.setFontColor(Color.black);
format1.setBackColor(Color.lightGray);
//使用条件格式设置交通灯
conditional.addRange(sheet.getAllocatedRange());
IConditionalFormat format = conditional.addCondition();
format.setFormatType(ConditionalFormatType.IconSet);
format.getIconSet().setIconSetType(IconSetType.ThreeTrafficLights1);
//保存文档
String result = "output/setTrafficLightsIcons_result.xlsx";
workbook.saveToFile(result, ExcelVersion.Version2013);
}
}
效果图: