【问题标题】:EPPlus Conditional Formatting String Length of Entire ColumnEPPlus 条件格式字符串整列长度
【发布时间】:2016-06-15 13:01:17
【问题描述】:

我正在使用 EPPlus 生成带有验证和条件格式的 Excel 文档。我想检查单元格中文本的长度,如果它大于指定长度,则用颜色填充它。我希望对整个专栏都这样做。

var address = new ExcelAddress("$A:$A");
var condition = workSheet.ConditionalFormatting.AddExpression(address);

condition.Formula = "=IF(LEN(A1)>25, TRUE, FALSE)";
condition.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
condition.Style.Fill.BackgroundColor.Color = Color.Green;

当我打开生成的 Excel 电子表格时,它会显示要求恢复数据的错误。

【问题讨论】:

    标签: c# excel excel-formula epplus


    【解决方案1】:

    对于像我一样查看此主题并在打开 excel 时遇到错误的人,请注意您不能使用“=”来启动条件表达式。

    另外,我的 Excel 公式区域格式规定我应该使用“;”表示多个参数,但在这种情况下,公式似乎像“,”作为分隔符。以下 sn-p 应该可以工作:

    var address = new ExcelAddress("A2");
    var condition = workSheet.ConditionalFormatting.AddExpression(address);
    
    condition.Formula = "IF(LEN(A1)>25, TRUE, FALSE)";
    condition.Style.Fill.BackgroundColor.Color = Color.Green;

    【讨论】:

      【解决方案2】:

      当我测试这个时

      using (var app = new ExcelPackage())
      {
         var workSheet = app.Workbook.Worksheets.Add("asdf");
         var address = new ExcelAddress("$A:$A");
         var condition = workSheet.ConditionalFormatting.AddExpression(address);
         workSheet.Cells["A1"].Value = "asdfasdfasdfasdfasdfasfdasd";
         condition.Formula = "=IF(LEN(A1)>25, TRUE, FALSE)";
         condition.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
         condition.Style.Fill.BackgroundColor.Color = System.Drawing.Color.Green;
         var destinationPath = @"../../GeneratedExcelFile.xlsx";
         File.WriteAllBytes(destinationPath, app.GetAsByteArray());
      }
      

      它没有导致任何错误,所以我认为问题是由您提供的代码以外的其他原因引起的

      【讨论】:

      • 您是否尝试过打开正在生成的 Excel 表格?它不会在服务器端引发错误。我运行了你提供的 sn-p,它生成一切正常,打开时会抛出错误。
      • 当我打开文件时,它确实没有抛出一个错误。
      【解决方案3】:

      这是一种全新的条件格式设置方法: 您可以使用 LINQ 根据您的情况检索单元格地址。只需确保在您的列表中添加用于存储 Excel 行号的附加属性(iRow 在下面)。

      string sRng = string.Join(",", YourModel.Where(l => l.YourColumn.Length > 25)
          .Select(a => "A" + 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); 
      }
      

      这种方法速度极快、更灵活,并且与条件格式不同,它不会牺牲 Excel 性能。以下是全文:

      https://www.codeproject.com/Tips/1231992/Conditional-Formatting-in-Excel-with-LINQ-and-EPPl

      EPPlus 有什么好处我没有看到范围地址的限制 - 在单个字符串中,您可以传递大约 15,000 - 20,000 个单元格的地址并立即格式化所有单元格。 唯一的缺点是,对于用户使用数据并希望查看格式如何变化(例如在 Excel 条件格式中)而言,它不是动态的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-07
        • 1970-01-01
        • 1970-01-01
        • 2014-02-24
        • 2017-04-20
        • 1970-01-01
        相关资源
        最近更新 更多