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

问题描述 投票:16回答:3

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

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

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

谢谢!

(抱歉我写的英文不好)

c# excel excel-2007 conditional-formatting epplus
3个回答
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-


2
投票

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

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


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希望这有助于将来的某个人。

© www.soinside.com 2019 - 2024. All rights reserved.