解决ExcelReport导出Excel报Number of rules must not exceed 3错误的问题

报错信息:

Number of rules must not exceed 3

[ArgumentException: Number of rules must not exceed 3]
   NPOI.XSSF.UserModel.XSSFSheetConditionalFormatting.AddConditionalFormatting(CellRangeAddress[] regions, IConditionalFormattingRule[] cfRules) +870
   NPOI.Extend.SheetExtend.CopyRows(ISheet sheet, Int32 startRowIndex, Int32 endRowIndex) +620
   ExcelReport.SheetAdapter.CopyRow(Int32 rowIndex, Action processTemplate) +37
   ExcelReport.TableFormatter`1.Format(SheetAdapter sheetAdapter) +485
   ExcelReport.SheetFormatter.Format(IWorkbook workbook) +225
   ExcelReport.Export.ExportToBuffer(String templateFile, SheetFormatter[] sheetFormatters) +46
   ExcelReport.ExportHelper.ExportToWeb(String templateFile, String targetFile, SheetFormatter[] sheetFormatters) +294

使用源代码进行调试发现错误原因在于ExcelReport调用的NPOI.Extend这个拓展的问题
有问题的方法:CellExtend类下的AddConditionalFormattingRules方法


cell.Sheet.SheetConditionalFormatting.AddConditionalFormatting(regions, cfrs); 该方法的cfrs数组最大长度只能支持3个条件格式规则

可以改为循环添加条件格式规则或者按长度判断,长度大于3则循环添加

原方法:

        /// <summary>
        ///     添加条件格式规则
        /// </summary>
        /// <param name="cell">单元格</param>
        /// <param name="cfrs">条件格式规则</param>
        public static void AddConditionalFormattingRules(this ICell cell, IConditionalFormattingRule[] cfrs)
        {
            CellRangeAddress[] regions =
            {
                new CellRangeAddress(cell.RowIndex, cell.RowIndex, cell.ColumnIndex, cell.ColumnIndex)
            };
            cell.Sheet.SheetConditionalFormatting.AddConditionalFormatting(regions, cfrs);
        }

更改后的方法:

        #region 1.0 添加条件格式规则

        /// <summary>
        ///     添加条件格式规则
        /// </summary>
        /// <param name="cell">单元格</param>
        /// <param name="cfrs">条件格式规则</param>
        public static void AddConditionalFormattingRules(this ICell cell, IConditionalFormattingRule[] cfrs)
        {
            CellRangeAddress[] regions =
            {
                new CellRangeAddress(cell.RowIndex, cell.RowIndex, cell.ColumnIndex, cell.ColumnIndex)
            };
            if (cfrs.Length <= 3)
            {
                cell.Sheet.SheetConditionalFormatting.AddConditionalFormatting(regions, cfrs);
            }
            else
            {
                foreach (var item in cfrs)
                {
                    cell.Sheet.SheetConditionalFormatting.AddConditionalFormatting(regions, item);
                }
            }

        }

NPOI.Extend版本:1.0.3

ExcelReport版本:2.0.1 

原文地址:https://www.cnblogs.com/townsend/p/7544174.html