2012-11-02 136 views
13

我想通过使用EPPlus的条件格式化功能来格式化某些范围。我阅读了许多文档,但没有提及有关条件格式表达式的内容。使用EPPlus通过表达式进行条件格式化

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

  1. 我们可以使用多个范围投入参数ExcelAddress(如 “H1:H17,L1:L17,” AA1:AA17" )
  2. 公式放入公式属性是有点像互操作Excel或不?(就像我们用“A1”来表示当前单元 在互操作格式化EXCEL)
  3. 你能给我使用条件格式表达一个小的演示代码腿。

谢谢!

(对不起,我写的英文不好)

回答

28

我已经自己找到了解决方案。请举个例子的代码:

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-

+0

可以提供“包含”文本条件格式 –

+1

这是Excel函数,我看到他们使用'ISNUMBER'和'SEARCH'函数。http://office.microsoft.com/en-001/excel-help/check-if-a-cell-contains-text-HP003056106.aspx – Han

+0

我想直接在Excel上使用条件格式,但我没有清楚的'当前'在您的表达。你用作表达式IF(AND(ISBLANK(OFFSET(B3,0,-1)),ISBLANK(B3)),1,0)',并且在代码注释中你说'//如果其中一个先前的单元格或当前单元格是空白:'。 “当前”单元格的引用在哪里?我只看到'B3'。 – jotapdiez

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 希望这可以帮助别人的未来。

相关问题