7

I am creating excel using EPPlus with conditional formatting. I am using C# code to do conditional formatting but its not working.

Please check my below code and let me know where I am wrong:

ExcelPackage pck = new ExcelPackage();
var ws = pck.Workbook.Worksheets.Add("Sample1");
var _formatRangeAddress = new ExcelAddress("H16:K31,H33:K44,H46:K57,H59:K69,H71:K73");
string _statement = "=AND(COUNTA(H16:H16)<2,COUNTA(H16:K16)>0)";
var _cond4 = ws.ConditionalFormatting.AddExpression(_formatRangeAddress);
_cond4.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
_cond4.Style.Fill.BackgroundColor.Color = Color.Green;
_cond4.Formula = _statement;
pck.SaveAs(Response.OutputStream);
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;  filename=Sample1.xlsx");
Tasos K.
  • 7,669
  • 7
  • 38
  • 57
Tarun Mathur
  • 855
  • 7
  • 25

2 Answers2

7

Set the formula string without the = at the beginning:

string _statement = "AND(COUNTA(H16:H16)<2,COUNTA(H16:K16)>0)";
[...]
_cond4.Formula = _statement;

The solution is mentioned here: Conditional Formatting by Expression using EPPlus

Community
  • 1
  • 1
Joanvo
  • 5,200
  • 2
  • 21
  • 34
1

Please try this:

ExcelPackage pck = new ExcelPackage();
var ws = pck.Workbook.Worksheets.Add("Sample1");
var _formatRangeAddress = new ExcelAddress("H16:K31,H33:K44,H46:K57,H59:K69,H71:K73");
string _statement = "AND(COUNTA(H16:H16)<2,COUNTA(H16:K16)>0)";
var _cond4 = ws.ConditionalFormatting.AddExpression(_formatRangeAddress);
_cond4.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
_cond4.Style.Fill.BackgroundColor.Color = Color.Green;
_cond4.Formula = _statement;
pck.SaveAs(Response.OutputStream);
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;  filename=Sample1.xlsx");
Benjamin W.
  • 33,075
  • 16
  • 78
  • 86
atul
  • 551
  • 4
  • 11