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

时间:2012-11-02 14:02:16

标签: c# excel excel-2007 conditional-formatting epplus

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

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

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

    (抱歉我写的英文不好)

3 个答案:

答案 0 :(得分:34)

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

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;

在上面的例子中,

  • _formatRangeAddress是将应用于的范围 表达式的条件格式。这是第一个细胞 范围将用于条件公式中。 (B3)。
  • _statement是 用于计算条件的公式,此字符串 以等号开头(=)(与MS Excel的差异点), 用于表达的细胞是细胞中的第一个细胞 _formatRangeAddress。 (B3)。

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

答案 1 :(得分:2)

在EPPlus的3.1 beta版本中支持条件格式。

在这里查看源代码:http://epplus.codeplex.com/discussions/348196/

答案 2 :(得分:0)

经过多次卫星后,我发现使用LINQ和EPPlus可以更加灵活快捷地实现这一目标。您需要做的就是:在列表中添加额外的属性以保存Excel行号,然后使用LINQ检索单元格地址。在这种情况下,它看起来像这样:

string sRng = string.Join(",", YourModel.Where(f => f.YourField == null)
    .Select(a => "H" + a.iRow + ",L" + a.iRow + ",AA" + a.iRow)); // this address could be many pages and it works

if (sRng.Length > 0) {
    ws.Cells[sRng].Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.Green); 
}

以下是完整文章:

https://www.codeproject.com/Tips/1231992/Conditional-Formatting-in-Excel-with-LINQ-and-EPPl

另见另一个例子:https://stackoverflow.com/a/49022692/8216122 希望这有助于将来的某些人。

相关问题