使用EPPlus通过表达式进行条件格式化

Han*_*Han 17 c# excel conditional-formatting excel-2007 epplus

我正在尝试使用EPPlus的条件格式化功能来格式化某个范围.我阅读了很多文档,但没有提到条件格式表达式.

我很困惑.不知道如何使用该功能.以下是我的一些问题:

  1. 我们可以使用多个范围放入参数ExcelAddress(如"H1:H17,L1:L17,"AA1:AA17")
  2. 公式被放入公式属性是否像Interop Excel一样?(就像我们使用"A1"来表示当前单元格在interop excel中进行格式化)
  3. 你能给我一个使用条件格式表达式的小型演示代码段吗?

谢谢!

(抱歉我写的英文不好)

Han*_*Han 35

我自己找到了解决方案.请拿一个示例代码:

ExcelAddress _formatRangeAddress = new ExcelAddress("B3:B10,D3:D10,F3:F10,H3:H10:J3:J10");
// fill WHITE color if previous cell or current cell is BLANK:
// B3 is the current cell because the range _formatRangeAddress starts from B3.
// OFFSET(B3,0,-1) returns the previous cell's value. It's excel function.
string _statement = "IF(OR(ISBLANK(OFFSET(B3,0,-1)),ISBLANK(B3)),1,0)";
var _cond4 = sheet.ConditionalFormatting.AddExpression(_formatRangeAddress);
_cond4.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
_cond4.Style.Fill.BackgroundColor.Color = Color.White;
_cond4.Formula = _statement;

// fill GREEN color if value of the current cell is greater than 
//    or equals to value of the previous cell
_statement = "IF(OFFSET(B3,0,-1)-B3<=0,1,0)";
var _cond1 = sheet.ConditionalFormatting.AddExpression(_formatRangeAddress);
_cond1.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
_cond1.Style.Fill.BackgroundColor.Color = Color.Green;
_cond1.Formula = _statement;

// fill RED color if value of the current cell is less than 
//    value of the previous cell
_statement = "IF(OFFSET(B3,0,-1)-B3>0,1,0)";
var _cond3 = sheet.ConditionalFormatting.AddExpression(_formatRangeAddress);
_cond3.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
_cond3.Style.Fill.BackgroundColor.Color = Color.Red;
_cond3.Formula = _statement;
Run Code Online (Sandbox Code Playgroud)

在上面的例子中,

  • _formatRangeAddress是表达式应用于条件格式的范围.该范围内的第一个单元格将用于条件公式中.(B3).
  • _statement是用于计算条件的公式,该字符串 以等号(=)(与MS Excel的差异点)开始,用于表达的单元格是第一个单元格 _formatRangeAddress.(B3).

希望这对有需要的人有所帮助.-Han-