Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format condition by expression EPPlus

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");
like image 366
Tarun Mathur Avatar asked Sep 02 '14 11:09

Tarun Mathur


People also ask

What is conditional formatting?

Conditional formatting makes it easy to highlight certain values or make particular cells easy to identify. This changes the appearance of a cell range based on a condition (or criteria). You can use conditional formatting to highlight cells that contain values which meet a certain condition.

Does EPPlus require Excel?

No, it does not require Excel to be installed on the server, as you can read in the docs: EPPlus is a . NET library that reads and writes Excel files using the Office Open XML format (xlsx). EPPlus has no dependencies other than .


2 Answers

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

like image 82
Joanvo Avatar answered Nov 14 '22 22:11

Joanvo


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");
like image 26
atul Avatar answered Nov 14 '22 22:11

atul