NPOI Excel/C#需要公式以程序方式更改条件格式的背景



我使用NPOI以编程方式创建Excel文件。其中一个要求是,它需要能够根据值更改单元格的背景-绿色表示好的数字,红色表示坏的数字,等等。我的一切都很完美,可以创建公式。。。但我一辈子都找不到一个能说明如何改变背景颜色的公式。无论我如何在谷歌上寻找答案,一切都只是想展示如何打开Excel和使用条件格式向导。我忽略了什么?有没有一种方法可以让我看到条件格式向导创建的公式,并将其复制粘贴到我的代码中?

以下是我设置的将字段更改为通过/失败的示例。。。但我的眼睛喜欢闪亮的颜色…

XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sh = (XSSFSheet)wb.CreateSheet("ACT");
string cf = "IF(" + engCell + (detailRow.RowNum + 1) + @">17,""Pass :)"", ""Fail :("")";
detailRow.CreateCell(detailIdx);
detailRow.GetCell(detailIdx).SetCellType(CellType.Formula);
detailRow.GetCell(detailIdx++).SetCellFormula(cf);

我想通了!!!我希望这可以帮助其他使用NPOIXSSF进行条件格式化的人:

XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sh = (XSSFSheet)wb.CreateSheet("ACT");
sh.CreateRow(0).CreateCell(0).SetCellValue(14);
sh.CreateRow(1).CreateCell(0).SetCellValue(20);
sh.CreateRow(2).CreateCell(0).SetCellValue(10);
sh.CreateRow(3).CreateCell(0).SetCellValue(23);
sh.CreateRow(4).CreateCell(0).SetCellValue(19);
sh.CreateRow(5).CreateCell(0).SetCellValue(14);
XSSFSheetConditionalFormatting sCF = (XSSFSheetConditionalFormatting)sh.SheetConditionalFormatting;
//Fill Green if Passing Score
XSSFConditionalFormattingRule cfGreen = 
(XSSFConditionalFormattingRule)sCF.CreateConditionalFormattingRule(ComparisonOperator.GreaterThanOrEqual, "19");
XSSFPatternFormatting fillGreen = (XSSFPatternFormatting)cfGreen.CreatePatternFormatting();
fillGreen.FillBackgroundColor = IndexedColors.LightGreen.Index;
fillGreen.FillPattern = FillPattern.SolidForeground;
//Fill Red if Passing Score
XSSFConditionalFormattingRule cfRed =
(XSSFConditionalFormattingRule)sCF.CreateConditionalFormattingRule(ComparisonOperator.LessThan, "19");
XSSFPatternFormatting fillRed = (XSSFPatternFormatting)cfRed.CreatePatternFormatting();
fillRed.FillBackgroundColor = IndexedColors.Red.Index;
fillRed.FillPattern = FillPattern.SolidForeground;
CellRangeAddress[] cfRange = { CellRangeAddress.ValueOf("A1:A6") };
sCF.AddConditionalFormatting(cfRange, cfGreen, cfRed);

最新更新