通过表达式EPPlus格式化条件

本文关键字:格式化 条件 EPPlus 表达式 | 更新日期: 2023-09-27 18:20:15

我正在使用带有条件格式的EPPlus创建excel。我正在使用C#代码进行条件格式化,但它不起作用。

请检查我下面的代码,让我知道我错在哪里:

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");

通过表达式EPPlus格式化条件

设置开头没有=的公式字符串:

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

这里提到了解决方案:使用EPPlus 通过表达式进行条件格式化

请尝试以下操作:

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");