在poi中设置条件格式也是使用如下代码
XSSFSheetConditionalFormatting scf = target.getSheetConditionalFormatting(); //获得条件格式对象//红色格式XSSFConditionalFormattingRule cf_R_rule = scf.createConditionalFormattingRule(ComparisonOperator.LT, "0", null);//设置条件格式规则XSSFFontFormatting cf_R = cf_R_rule.createFontFormatting();//创建字体样式cf_R.setFontColorIndex(IndexedColors.RED.index);//条件格式应用的单元格范围 CellRangeAddress[] regions = {new CellRangeAddress(4, 26, 4, 4),new CellRangeAddress(4, 26, 12, 12),new CellRangeAddress(4, 26, 23, 23),new CellRangeAddress(37, 54, 4, 4),new CellRangeAddress(37, 54, 12, 12),new CellRangeAddress(37, 54, 23, 23)};//XSSFConditionalFormattingRule[] cfRules = {cf_R_rule}; scf.addConditionalFormatting(regions, cf_R_rule);
现在需求使用自定义的颜色来设置字体是可以采用
XSSFConditionalFormattingRule cf_W_rule_1 = scf.createConditionalFormattingRule(ComparisonOperator.EQUAL, "0", null);//设置条件格式规则XSSFFontFormatting cf_W_1 = cf_W_rule_1.createFontFormatting();//创建字体样式XSSFColor xssfColor = new XSSFColor(new java.awt.Color(204,255, 255));cf_W_1.setFontColorIndex(xssfColor.getIndex());cf_W_1.setFontColor(xssfColor);
这里的重点是先设置setFontColorIndex在设置setFontColor,原因是直接使用setFontColor会报数组越界异常,他源代码里面没有初始化数组,而setColorIndex会初始数组
cf_W_1.setFontColorIndex(xssfColor.getIndex());cf_W_1.setFontColor(xssfColor);