diff --git a/src/EPPlus/ConditionalFormatting/ExcelConditionalFormattingIconSetBase.cs b/src/EPPlus/ConditionalFormatting/ExcelConditionalFormattingIconSetBase.cs index 7f2652cd3..99a79416d 100644 --- a/src/EPPlus/ConditionalFormatting/ExcelConditionalFormattingIconSetBase.cs +++ b/src/EPPlus/ConditionalFormatting/ExcelConditionalFormattingIconSetBase.cs @@ -330,6 +330,30 @@ internal List GetCustomIconList(bool return customIconList; } + double[] _sortedPercentileValues = null; + + /// + /// Number of cached values less than . + /// The values are sorted once per export instead of scanning the cache for every cell. + /// + private int CountValuesLessThan(double value) + { + if (_sortedPercentileValues == null) + { + //NaN is never less than another value, so leave it out. + _sortedPercentileValues = cellValueCache.Select(n => Convert.ToDouble(n)).Where(d => double.IsNaN(d) == false).ToArray(); + Array.Sort(_sortedPercentileValues); + } + if (double.IsNaN(value)) return 0; + return CFRangeValues.CountLessThan(_sortedPercentileValues, value); + } + + internal override void RemoveTempExportData() + { + base.RemoveTempExportData(); + _sortedPercentileValues = null; + } + protected int CalculateCorrectIcon(ExcelAddress address, ExcelConditionalFormattingIconDataBarValue[] icons) { //Icon1.Type @@ -337,9 +361,10 @@ protected int CalculateCorrectIcon(ExcelAddress address, ExcelConditionalFormatt var cellValue = range.Value; if(cellValue.IsNumeric() && cellValue != null) { - if (cellValueCache.Count == 0) + if (_cellValueCacheUpdated == false) { UpdateCellValueCache(false, true); + _sortedPercentileValues = null; } double percentile = -1d; @@ -366,7 +391,7 @@ protected int CalculateCorrectIcon(ExcelAddress address, ExcelConditionalFormatt { if(percentile == -1) { - double numValuesLessThan = cellValueCache.Where(n => Convert.ToDouble(n) < cellValueAsDouble).Count(); + double numValuesLessThan = CountValuesLessThan(cellValueAsDouble); percentile = (numValuesLessThan / (cellValueCache.Count() - 1d)) * 100d; } diff --git a/src/EPPlus/ConditionalFormatting/Rules/CFRangeValues.cs b/src/EPPlus/ConditionalFormatting/Rules/CFRangeValues.cs new file mode 100644 index 000000000..335055297 --- /dev/null +++ b/src/EPPlus/ConditionalFormatting/Rules/CFRangeValues.cs @@ -0,0 +1,93 @@ +/************************************************************************************************* + Required Notice: Copyright (C) EPPlus Software AB. + This software is licensed under PolyForm Noncommercial License 1.0.0 + and may only be used for noncommercial purposes + https://polyformproject.org/licenses/noncommercial/1.0.0/ + + A commercial license to use this software can be purchased at https://epplussoftware.com + ************************************************************************************************* + Date Author Change + ************************************************************************************************* + 11/25/2026 EPPlus Software AB Avoid walking empty cells in conditional formatting ranges + *************************************************************************************************/ +using OfficeOpenXml.Core.CellStore; +using System; +using System.Collections.Generic; + +namespace OfficeOpenXml.ConditionalFormatting.Rules +{ + /// + /// Helpers for reading the values in a conditional formatting range without visiting empty cells. + /// The range (sqref) of a rule can cover a whole sheet, so walking it cell by cell is not an option. + /// + internal static class CFRangeValues + { + /// + /// Returns the non-null values in the address. + /// Sub-addresses are handled in order and each one is returned row by row, column by column, + /// which is the same order as walking every cell of the address. + /// Cells covered by more than one sub-address are returned once per sub-address. + /// + internal static List GetValues(ExcelWorksheet ws, ExcelAddressBase address) + { + var result = new List(); + var cells = new List>(); + foreach (var a in address.GetAllAddresses()) + { + cells.Clear(); + var e = new CellStoreEnumerator(ws._values, a._fromRow, a._fromCol, a._toRow, a._toCol); + while (e.Next()) + { + var row = e.Row; + var col = e.Column; + if (row < a._fromRow || row > a._toRow || col < a._fromCol || col > a._toCol) continue; + var v = ws.GetValue(row, col); + if (v != null) + { + cells.Add(new KeyValuePair(((long)row << 16) | (uint)col, v)); + } + } + cells.Sort((x, y) => x.Key.CompareTo(y.Key)); + foreach (var c in cells) + { + result.Add(c.Value); + } + } + return result; + } + + /// + /// Total number of cells in the address, including empty cells. Cells covered by more than one sub-address are counted once per sub-address. + /// + internal static long GetCellCount(ExcelAddressBase address) + { + long count = 0; + foreach (var a in address.GetAllAddresses()) + { + count += (long)a.Rows * a.Columns; + } + return count; + } + + /// + /// Returns the number of items in the sorted array that are less than , using ordering (NaN sorts first). + /// + internal static int CountLessThan(double[] sorted, double value) + { + int lo = 0, hi = sorted.Length; + while (lo < hi) + { + int mid = lo + ((hi - lo) >> 1); + if (sorted[mid].CompareTo(value) < 0) + { + lo = mid + 1; + } + else + { + hi = mid; + } + } + return lo; + } + } +} diff --git a/src/EPPlus/ConditionalFormatting/Rules/CachingCF.cs b/src/EPPlus/ConditionalFormatting/Rules/CachingCF.cs index ce99d77b1..87939d3ab 100644 --- a/src/EPPlus/ConditionalFormatting/Rules/CachingCF.cs +++ b/src/EPPlus/ConditionalFormatting/Rules/CachingCF.cs @@ -48,50 +48,45 @@ internal override ExcelConditionalFormattingRule Clone(ExcelWorksheet newWs = nu } protected List cellValueCache = new List(); + /// + /// True when has been filled for the current export. + /// + protected bool _cellValueCacheUpdated = false; protected virtual void UpdateCellValueCache(bool asStrings = false, bool cacheOnlyNumeric = false) { cellValueCache.Clear(); - foreach (var cell in Address.GetAllAddresses()) + //Only visit cells that exist. The rule's range can cover a full sheet. + foreach (var value in CFRangeValues.GetValues(_ws, Address)) { - for (int i = 1; i <= cell.Rows; i++) + if (asStrings) + { + cellValueCache.Add(value.ToString()); + } + else { - for (int j = 1; j <= cell.Columns; j++) + if (cacheOnlyNumeric) { - var row = cell._fromRow + i - 1; - var col = cell._fromCol + j - 1; - var value = _ws.Cells[row, col].Value; - if (value != null) + if (value.IsNumeric()) { - if (asStrings) - { - cellValueCache.Add(value.ToString()); - } - else - { - if(cacheOnlyNumeric) - { - if(value.IsNumeric()) - { - cellValueCache.Add(value); - } - } - else - { - cellValueCache.Add(value); - } - } + cellValueCache.Add(value); } } + else + { + cellValueCache.Add(value); + } } } + _cellValueCacheUpdated = true; } internal override void RemoveTempExportData() { base.RemoveTempExportData(); cellValueCache.Clear(); + _cellValueCacheUpdated = false; } } } diff --git a/src/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingAverageGroup.cs b/src/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingAverageGroup.cs index fa4ecd7b2..2bd3ba8d8 100644 --- a/src/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingAverageGroup.cs +++ b/src/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingAverageGroup.cs @@ -42,6 +42,14 @@ internal ExcelConditionalFormattingAverageGroup(ExcelConditionalFormattingAverag //TODO: This needs to be cleared if this CF ever changes. double? average = null; + bool _isAverageCalculated = false; + + internal override void RemoveTempExportData() + { + base.RemoveTempExportData(); + average = null; + _isAverageCalculated = false; + } internal override bool ShouldApplyToCell(ExcelAddress address) { @@ -49,8 +57,10 @@ internal override bool ShouldApplyToCell(ExcelAddress address) { if (_ws.Cells[address.Address].Value.IsNumeric()) { - if (average == null) + //Calculate once per export, also when the result is not numeric. + if (_isAverageCalculated == false) { + _isAverageCalculated = true; var avgFormula = $"AVERAGE({Address})"; var avgResult = _ws.Workbook.FormulaParserManager.Parse(avgFormula, address.FullAddress, false).ToString(); diff --git a/src/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingDataBar.cs b/src/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingDataBar.cs index 1600dc50f..6288ace41 100644 --- a/src/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingDataBar.cs +++ b/src/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingDataBar.cs @@ -329,6 +329,26 @@ internal override bool ShouldApplyToCell(ExcelAddress address) return false; } + double? _cachedMaximum = null; + double? _cachedMinimum = null; + + /// + /// A percentile is calculated over the whole range, so it is the same for every cell. + /// Calculate it once per export instead of once per cell. + /// + private double GetCalculatedValue(ExcelConditionalFormattingIconDataBarValue value, ref double? cachedValue, ExcelAddressBase address) + { + if (value.Type == eExcelConditionalFormattingValueObjectType.Percentile) + { + if (cachedValue.HasValue == false) + { + cachedValue = value.GetCalculatedValue(highest, lowest, _ws.Workbook, address, Address, cellValueCache); + } + return cachedValue.Value; + } + return value.GetCalculatedValue(highest, lowest, _ws.Workbook, address, Address, cellValueCache); + } + internal double GetPercentageAtCell(ExcelAddressBase address) { var range = _ws.Cells[address.Address]; @@ -337,15 +357,15 @@ internal double GetPercentageAtCell(ExcelAddressBase address) if (cellValue.IsNumeric() && FillColor.GetColorAsColor() != Color.Empty) { - if (cellValueCache.Count == 0) + if (_cellValueCacheUpdated == false) { UpdateCellValueCache(false, true); } var realValue = Convert.ToDouble(cellValue); - var maximum = HighValue.GetCalculatedValue(highest, lowest, _ws.Workbook, address, Address, cellValueCache); - var minimum = LowValue.GetCalculatedValue(highest, lowest, _ws.Workbook, address, Address, cellValueCache); + var maximum = GetCalculatedValue(HighValue, ref _cachedMaximum, address); + var minimum = GetCalculatedValue(LowValue, ref _cachedMinimum, address); if (AxisPosition != eExcelDatabarAxisPosition.None) { @@ -440,6 +460,8 @@ internal override void RemoveTempExportData() base.RemoveTempExportData(); highest = double.NaN; lowest = double.NaN; + _cachedMaximum = null; + _cachedMinimum = null; } //internal bool GetHasNegativeBar() diff --git a/src/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingDuplicateValues.cs b/src/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingDuplicateValues.cs index 8394cc100..2c15f821a 100644 --- a/src/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingDuplicateValues.cs +++ b/src/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingDuplicateValues.cs @@ -40,23 +40,23 @@ internal ExcelConditionalFormattingDuplicateValues( { } - //HashSet duplicates = new HashSet(); - IEnumerable duplicates; + HashSet duplicates; internal override bool ShouldApplyToCell(ExcelAddress address) { - if(cellValueCache.Count == 0) + if(_cellValueCacheUpdated == false || duplicates == null) { UpdateCellValueCache(true); - duplicates = cellValueCache.GroupBy(value => value.ToString().ToUpper()) + //Materialize the set once per export. A deferred query here is re-evaluated for every cell. + duplicates = new HashSet(cellValueCache.GroupBy(value => value.ToString().ToUpper()) .Where(key => key.Count() > 1) - .Select(group => group.Key); + .Select(group => group.Key)); } - if(_ws.Cells[address.Address].Value != null) + var cellValue = _ws.Cells[address.Address].Value; + if (cellValue != null) { - var cellVal = _ws.Cells[address.Address].Value.ToString(); - return duplicates.Contains(_ws.Cells[address.Address].Value.ToString().ToUpper()); + return duplicates.Contains(cellValue.ToString().ToUpper()); } return false; } diff --git a/src/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingStdDevGroup.cs b/src/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingStdDevGroup.cs index 15c106d93..78d39d30e 100644 --- a/src/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingStdDevGroup.cs +++ b/src/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingStdDevGroup.cs @@ -63,6 +63,16 @@ internal override void ReadClassSpecificXmlNodes(XmlReader xr) StdDev = UInt16.Parse(xr.GetAttribute("stdDev")); } + bool _isCalculated = false; + bool _stdDevParsable, _avgParsable; + double _stdDevValue, _avgValue; + + internal override void RemoveTempExportData() + { + base.RemoveTempExportData(); + _isCalculated = false; + } + internal override bool ShouldApplyToCell(ExcelAddress address) { if (_ws.Cells[address.Address].Value == null) @@ -76,16 +86,24 @@ internal override bool ShouldApplyToCell(ExcelAddress address) var addressValue = Convert.ToDouble(_ws.Cells[address.Address].Value); - var stdDevFormula = $"{StdDev}*STDEV.S({Address})"; - var avgFormula = $"AVERAGE({Address})"; + //The standard deviation and average are the same for every cell in the range, so calculate them once per export. + if (_isCalculated == false) + { + var stdDevFormula = $"{StdDev}*STDEV.S({Address})"; + var avgFormula = $"AVERAGE({Address})"; + + var stdDevRes = _ws.Workbook.FormulaParserManager.Parse(stdDevFormula, address.FullAddress, false).ToString(); + var avgResult = _ws.Workbook.FormulaParserManager.Parse(avgFormula, address.FullAddress, false).ToString(); - var stdDevRes = _ws.Workbook.FormulaParserManager.Parse(stdDevFormula, address.FullAddress, false).ToString(); - var avgResult = _ws.Workbook.FormulaParserManager.Parse(avgFormula, address.FullAddress, false).ToString(); + _stdDevParsable = double.TryParse(stdDevRes, out _stdDevValue); + _avgParsable = double.TryParse(avgResult, out _avgValue); + _isCalculated = true; + } - var stdParsable = double.TryParse(stdDevRes, out double stdDevDouble); - var avgParsable = double.TryParse(avgResult, out double avgDouble); + if (!(_stdDevParsable && _avgParsable)) { return false; } - if (!(stdParsable && avgParsable)) { return false; } + var stdDevDouble = _stdDevValue; + var avgDouble = _avgValue; switch (Type) { diff --git a/src/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingThreeColorScale.cs b/src/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingThreeColorScale.cs index 5eba27848..8e5a02d67 100644 --- a/src/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingThreeColorScale.cs +++ b/src/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingThreeColorScale.cs @@ -159,30 +159,11 @@ internal override string ApplyStyleOverride(ExcelAddress address) if (cellValue.IsNumeric()) { - var cellValues = new List(); - double average = 0; - int count = 0; - foreach (var cell in Address.GetAllAddresses()) - { - for (int i = 1; i <= cell.Rows; i++) - { - for (int j = 1; j <= cell.Columns; j++) - { - cellValues.Add(ConvertUtil.GetValueDouble(_ws.Cells[cell._fromRow + i - 1, cell._fromCol + j - 1].Value)); - average += ConvertUtil.GetValueDouble(_ws.Cells[cell._fromRow + i - 1, cell._fromCol + j - 1].Value); - count++; - } - } - } - - average = average / count; - - var values = cellValues.OrderBy(n => n); - - var aValue = cellValues.Last(); + var cache = GetExportCache(); + double average = cache.Sum / cache.TotalCount; - var highest = Convert.ToDouble(values.Last()); - var lowest = Convert.ToDouble(values.First()); + var highest = cache.Highest; + var lowest = cache.Lowest; //midPoint = (highest + lowest) * 0.5; var realValue = Convert.ToDouble(cellValue); diff --git a/src/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingTopBottomGroup.cs b/src/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingTopBottomGroup.cs index e2bac5056..24de5e9d8 100644 --- a/src/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingTopBottomGroup.cs +++ b/src/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingTopBottomGroup.cs @@ -58,48 +58,52 @@ internal override ExcelConditionalFormattingRule Clone(ExcelWorksheet newWs = nu return new ExcelConditionalFormattingTopBottomGroup(this, newWs); } + HashSet _matchingValues; + + internal override void RemoveTempExportData() + { + base.RemoveTempExportData(); + _matchingValues = null; + } + internal override bool ShouldApplyToCell(ExcelAddress address) { - if (_ws.Cells[address.Address].Value.IsNumeric()) + var cellValue = _ws.Cells[address.Address].Value; + if (cellValue.IsNumeric()) { - if(cellValueCache.Count == 0) + if(_cellValueCacheUpdated == false || _matchingValues == null) { UpdateCellValueCache(); + //Sort once per export and keep the qualifying values. Sorting per cell is O(n^2 log n). + _matchingValues = GetMatchingValues(); } - switch (Type) - { - case eExcelConditionalFormattingRuleType.Top: - var sorted = cellValueCache.Where(n => n.IsNumeric()).OrderByDescending(n => n).Take(Rank); - if (sorted.Contains(_ws.Cells[address.Address].Value)) - { - return true; - } - break; - case eExcelConditionalFormattingRuleType.TopPercent: - var percentDescending = cellValueCache.Where(n => n.IsNumeric()).OrderByDescending(n => n).Take(cellValueCache.Count * Rank / 100); - if (percentDescending.Contains(_ws.Cells[address.Address].Value)) - { - return true; - } - break; - case eExcelConditionalFormattingRuleType.Bottom: - var bottomSorted = cellValueCache.Where(n => n.IsNumeric()).OrderBy(n => n).Take(Rank); - if (bottomSorted.Contains(_ws.Cells[address.Address].Value)) - { - return true; - } - break; - case eExcelConditionalFormattingRuleType.BottomPercent: - var percentAscending = cellValueCache.Where(n => n.IsNumeric()).OrderBy(n => n).Take(cellValueCache.Count * Rank / 100); - if (percentAscending.Contains(_ws.Cells[address.Address].Value)) - { - return true; - } - break; - } + return _matchingValues != null && _matchingValues.Contains(cellValue); } return false; } + + private HashSet GetMatchingValues() + { + IEnumerable values; + switch (Type) + { + case eExcelConditionalFormattingRuleType.Top: + values = cellValueCache.Where(n => n.IsNumeric()).OrderByDescending(n => n).Take(Rank); + break; + case eExcelConditionalFormattingRuleType.TopPercent: + values = cellValueCache.Where(n => n.IsNumeric()).OrderByDescending(n => n).Take(cellValueCache.Count * Rank / 100); + break; + case eExcelConditionalFormattingRuleType.Bottom: + values = cellValueCache.Where(n => n.IsNumeric()).OrderBy(n => n).Take(Rank); + break; + case eExcelConditionalFormattingRuleType.BottomPercent: + values = cellValueCache.Where(n => n.IsNumeric()).OrderBy(n => n).Take(cellValueCache.Count * Rank / 100); + break; + default: + return new HashSet(); + } + return new HashSet(values); + } } } diff --git a/src/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingTwoColorScale.cs b/src/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingTwoColorScale.cs index 3b1f85d55..aa8fc3613 100644 --- a/src/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingTwoColorScale.cs +++ b/src/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingTwoColorScale.cs @@ -25,6 +25,7 @@ Date Author Change using OfficeOpenXml.Style; using OfficeOpenXml.FormulaParsing.Excel.Functions.MathFunctions; using OfficeOpenXml.Utils.TypeConversion; +using OfficeOpenXml.ConditionalFormatting.Rules; namespace OfficeOpenXml.ConditionalFormatting { @@ -218,38 +219,105 @@ public ExcelConditionalFormattingColorScaleValue HighValue set { _highValue = value; } } - internal virtual string ApplyStyleOverride(ExcelAddress address) + /// + /// Values of the rule's range, collected once per export. + /// Empty cells count as zero, as they did when the range was walked cell by cell, but they are not stored. + /// + internal class ColorScaleExportCache { - var range = _ws.Cells[address.Address]; - var cellValue = ConvertUtil.GetValueDouble(range.Value); - //TODO: Cache this for performance - if (cellValue.IsNumeric()) + /// Values of the non-empty cells, sorted using double.CompareTo (NaN first). + internal double[] SortedValues; + /// Number of empty cells. Each one counts as the value zero. + internal long EmptyCount; + /// Total number of cells, including empty cells. + internal long TotalCount; + /// Sum of all values, added in row/column order. + internal double Sum; + + internal double Lowest { - var cellValues = new List(); - foreach (var cell in Address.GetAllAddresses()) + get { - for (int i = 1; i <= cell.Rows; i++) - { - for (int j = 1; j <= cell.Columns; j++) - { - cellValues.Add(ConvertUtil.GetValueDouble(_ws.Cells[cell._fromRow + i - 1, cell._fromCol + j - 1].Value)); - } - } + if (SortedValues.Length == 0) return 0D; + if (EmptyCount > 0 && 0D.CompareTo(SortedValues[0]) < 0) return 0D; + return SortedValues[0]; } + } - var values = cellValues.OrderBy(n => n); - int index = 0; + internal double Highest + { + get + { + if (SortedValues.Length == 0) return 0D; + var last = SortedValues[SortedValues.Length - 1]; + if (EmptyCount > 0 && 0D.CompareTo(last) > 0) return 0D; + return last; + } + } - foreach(var value in values) + /// + /// The position of the first occurrence of in the sorted values of all cells. + /// + internal long IndexOf(double value) + { + if (double.IsNaN(value)) + { + return TotalCount; //Never equal to any value. + } + long index = CFRangeValues.CountLessThan(SortedValues, value); + if (0D.CompareTo(value) < 0) { - if (value == cellValue) - { - break; - } - index++; + index += EmptyCount; } + return index; + } + } + + ColorScaleExportCache _exportCache = null; + + internal ColorScaleExportCache GetExportCache() + { + if (_exportCache == null) + { + //Only visit cells that exist. The rule's range can cover a full sheet. + var values = CFRangeValues.GetValues(_ws, Address); + var sorted = new double[values.Count]; + double sum = 0D; + for (int i = 0; i < values.Count; i++) + { + var d = ConvertUtil.GetValueDouble(values[i]); + sorted[i] = d; + sum += d; + } + Array.Sort(sorted); + var total = CFRangeValues.GetCellCount(Address); + _exportCache = new ColorScaleExportCache() + { + SortedValues = sorted, + TotalCount = total, + EmptyCount = total - sorted.Length, + Sum = sum + }; + } + return _exportCache; + } + + internal override void RemoveTempExportData() + { + base.RemoveTempExportData(); + _exportCache = null; + } + + internal virtual string ApplyStyleOverride(ExcelAddress address) + { + var range = _ws.Cells[address.Address]; + var cellValue = ConvertUtil.GetValueDouble(range.Value); + if (cellValue.IsNumeric()) + { + var cache = GetExportCache(); + var index = cache.IndexOf(cellValue); - var newColor = CalculateNumberedGradient(index, values.Count()-1, LowValue.ColorSettings.GetColorAsColor(), HighValue.ColorSettings.GetColorAsColor()); + var newColor = CalculateNumberedGradient(index, cache.TotalCount - 1, LowValue.ColorSettings.GetColorAsColor(), HighValue.ColorSettings.GetColorAsColor()); return "background-color:" + "#" + newColor.ToArgb().ToString("x8").Substring(2) + ";"; } diff --git a/src/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingUniqueValues.cs b/src/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingUniqueValues.cs index 05d90eeca..aab6eb5bc 100644 --- a/src/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingUniqueValues.cs +++ b/src/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingUniqueValues.cs @@ -54,7 +54,7 @@ internal ExcelConditionalFormattingUniqueValues(ExcelConditionalFormattingUnique Rank = copy.Rank; } - IEnumerable uniques; + HashSet uniques; internal override void RemoveTempExportData() { @@ -64,12 +64,13 @@ internal override void RemoveTempExportData() internal override bool ShouldApplyToCell(ExcelAddress address) { - if(cellValueCache.Count == 0) + if(_cellValueCacheUpdated == false || uniques == null) { UpdateCellValueCache(); - uniques = cellValueCache.GroupBy(i => i) + //Materialize the set once per export. A deferred query here is re-evaluated for every cell. + uniques = new HashSet(cellValueCache.GroupBy(i => i) .Where(g => g.Count() == 1) - .Select(g => g.First()); + .Select(g => g.First())); } if(uniques.Contains(_ws.Cells[address.Address].Value)) diff --git a/src/EPPlus/Export/HtmlExport/Exporters/Internal/HtmlExporterBaseInternal.cs b/src/EPPlus/Export/HtmlExport/Exporters/Internal/HtmlExporterBaseInternal.cs index 550687db2..addf919a7 100644 --- a/src/EPPlus/Export/HtmlExport/Exporters/Internal/HtmlExporterBaseInternal.cs +++ b/src/EPPlus/Export/HtmlExport/Exporters/Internal/HtmlExporterBaseInternal.cs @@ -226,80 +226,87 @@ protected HTMLElement GetTableBody(ExcelRangeBase range, int row, int endRow) var ws = range.Worksheet; HtmlImage image = null; bool hasFooter = table != null && table.ShowTotal; - while (row <= endRow) + //Conditional formatting rules cache values from their range during the export. Make sure no cache is left from an earlier export or from a failed one. + range.Worksheet.ConditionalFormatting.ClearTempExportCacheForAllCFs(); + try { - EpplusHtmlAttribute attribute = null; - if (HandleHiddenRow(attribute, range.Worksheet, Settings, ref row)) - { - continue; //The row is hidden and should not be included. - } - - HTMLElement tFoot = null; - if (hasFooter && row == endRow) + while (row <= endRow) { - tFoot = new HTMLElement(HtmlElements.TFoot); - if (attribute != null) { tFoot.AddAttribute(attribute.AttributeName, attribute.Value); } - attribute = null; - } + EpplusHtmlAttribute attribute = null; + if (HandleHiddenRow(attribute, range.Worksheet, Settings, ref row)) + { + continue; //The row is hidden and should not be included. + } - var tr = new HTMLElement(HtmlElements.TableRow); + HTMLElement tFoot = null; + if (hasFooter && row == endRow) + { + tFoot = new HTMLElement(HtmlElements.TFoot); + if (attribute != null) { tFoot.AddAttribute(attribute.AttributeName, attribute.Value); } + attribute = null; + } - if (attribute != null) { tr.AddAttribute(attribute.AttributeName, attribute.Value); } + var tr = new HTMLElement(HtmlElements.TableRow); - if (Settings.Accessibility.TableSettings.AddAccessibilityAttributes) - { - tr.AddAttribute("role", "row"); + if (attribute != null) { tr.AddAttribute(attribute.AttributeName, attribute.Value); } - if (table == null || !table.ShowFirstColumn && !table.ShowLastColumn) + if (Settings.Accessibility.TableSettings.AddAccessibilityAttributes) { - tr.AddAttribute("scope", "row"); + tr.AddAttribute("role", "row"); + + if (table == null || !table.ShowFirstColumn && !table.ShowLastColumn) + { + tr.AddAttribute("scope", "row"); + } } - } - if (Settings.SetRowHeight) AddRowHeightStyle(tr, range, row, Settings.StyleClassPrefix, IsMultiSheet); + if (Settings.SetRowHeight) AddRowHeightStyle(tr, range, row, Settings.StyleClassPrefix, IsMultiSheet); - foreach (var col in _columns) - { - if (InMergeCellSpan(row, col)) continue; - var colIx = col - range._fromCol; - var cell = ws.Cells[row, col]; + foreach (var col in _columns) + { + if (InMergeCellSpan(row, col)) continue; + var colIx = col - range._fromCol; + var cell = ws.Cells[row, col]; - var dataType = HtmlRawDataProvider.GetHtmlDataTypeFromValue(cell.Value); + var dataType = HtmlRawDataProvider.GetHtmlDataTypeFromValue(cell.Value); - var tblData = new HTMLElement(HtmlElements.TableData); + var tblData = new HTMLElement(HtmlElements.TableData); - SetColRowSpan(range, tblData, cell); + SetColRowSpan(range, tblData, cell); - if ((Settings.Pictures.Include == ePictureInclude.Include) || (Settings.Pictures.Include == ePictureInclude.IncludeInHtmlOnly)) - { - image = GetImage(cell.Worksheet.PositionId, cell._fromRow, cell._fromCol); - } + if ((Settings.Pictures.Include == ePictureInclude.Include) || (Settings.Pictures.Include == ePictureInclude.IncludeInHtmlOnly)) + { + image = GetImage(cell.Worksheet.PositionId, cell._fromRow, cell._fromCol); + } - if (cell.Hyperlink == null) - { - var addRowScope = table == null ? false : table.ShowFirstColumn && col == table.Address._fromCol || table.ShowLastColumn && col == table.Address._toCol; - AddTableDataFromCell(cell, dataType, tblData, Settings, addRowScope, image, _exporterContext); - } - else - { - GetClassData(tblData, table != null, image, cell, Settings, _exporterContext, out HTMLElement contentElement); + if (cell.Hyperlink == null) + { + var addRowScope = table == null ? false : table.ShowFirstColumn && col == table.Address._fromCol || table.ShowLastColumn && col == table.Address._toCol; + AddTableDataFromCell(cell, dataType, tblData, Settings, addRowScope, image, _exporterContext); + } + else + { + GetClassData(tblData, table != null, image, cell, Settings, _exporterContext, out HTMLElement contentElement); - AddImage(contentElement, Settings, image, cell.Value); - AddHyperlink(contentElement, cell, Settings); + AddImage(contentElement, Settings, image, cell.Value); + AddHyperlink(contentElement, cell, Settings); + } + tr.AddChildElement(tblData); } - tr.AddChildElement(tblData); - } - tBody.AddChildElement(tr); + tBody.AddChildElement(tr); - if (tFoot != null) - { - tBody.AddChildElement(tFoot); + if (tFoot != null) + { + tBody.AddChildElement(tFoot); + } + row++; } - row++; } - - range.Worksheet.ConditionalFormatting.ClearTempExportCacheForAllCFs(); + finally + { + range.Worksheet.ConditionalFormatting.ClearTempExportCacheForAllCFs(); + } return tBody; } diff --git a/src/EPPlusTest/Export/HtmlExport/HtmlConditionalFormattingPerformanceTests.cs b/src/EPPlusTest/Export/HtmlExport/HtmlConditionalFormattingPerformanceTests.cs new file mode 100644 index 000000000..92e91e4a2 --- /dev/null +++ b/src/EPPlusTest/Export/HtmlExport/HtmlConditionalFormattingPerformanceTests.cs @@ -0,0 +1,195 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using OfficeOpenXml; +using OfficeOpenXml.ConditionalFormatting; +using System; +using System.Diagnostics; +using System.Drawing; + +namespace EPPlusTest.Export.HtmlExport +{ + /// + /// Conditional formatting rules that compare a cell against the whole range must not re-evaluate the range for every cell, + /// and must not walk the empty cells of a range that covers a full sheet. + /// + [TestClass] + public class HtmlConditionalFormattingPerformanceTests : TestBase + { + const int LargeRowCount = 50000; + static readonly TimeSpan MaxExportTime = TimeSpan.FromSeconds(30); + + private static ExcelWorksheet CreateSheet(ExcelPackage p, int rows) + { + var ws = p.Workbook.Worksheets.Add("Sheet1"); + for (int r = 1; r <= rows; r++) + { + ws.Cells[r, 1].Value = r % 7; + } + return ws; + } + + private static void AssertExportIsFast(ExcelRangeBase range) + { + var sw = Stopwatch.StartNew(); + var html = range.CreateHtmlExporter().GetHtmlString(); + sw.Stop(); + Assert.IsFalse(string.IsNullOrEmpty(html)); + Assert.IsTrue(sw.Elapsed < MaxExportTime, $"Html export took {sw.Elapsed}."); + } + + [TestMethod] + public void DuplicateValuesOnLargeRangeShouldExportInLinearTime() + { + using (var p = new ExcelPackage()) + { + var ws = CreateSheet(p, LargeRowCount); + var range = ws.Cells[1, 1, LargeRowCount, 1]; + range.ConditionalFormatting.AddDuplicateValues(); + AssertExportIsFast(range); + } + } + + [TestMethod] + public void UniqueValuesOnLargeRangeShouldExportInLinearTime() + { + using (var p = new ExcelPackage()) + { + var ws = CreateSheet(p, LargeRowCount); + var range = ws.Cells[1, 1, LargeRowCount, 1]; + range.ConditionalFormatting.AddUniqueValues(); + AssertExportIsFast(range); + } + } + + [TestMethod] + public void TopBottomOnLargeRangeShouldExportInLinearTime() + { + using (var p = new ExcelPackage()) + { + var ws = CreateSheet(p, LargeRowCount); + var range = ws.Cells[1, 1, LargeRowCount, 1]; + range.ConditionalFormatting.AddTop(); + range.ConditionalFormatting.AddTopPercent(); + range.ConditionalFormatting.AddBottom(); + range.ConditionalFormatting.AddBottomPercent(); + AssertExportIsFast(range); + } + } + + [TestMethod] + public void ColorScalesOnLargeRangeShouldExportInLinearTime() + { + using (var p = new ExcelPackage()) + { + var ws = CreateSheet(p, LargeRowCount); + var range = ws.Cells[1, 1, LargeRowCount, 1]; + range.ConditionalFormatting.AddTwoColorScale(); + range.ConditionalFormatting.AddThreeColorScale(); + AssertExportIsFast(range); + } + } + + [TestMethod] + public void StdDevOnLargeRangeShouldExportInLinearTime() + { + using (var p = new ExcelPackage()) + { + var ws = CreateSheet(p, LargeRowCount); + var range = ws.Cells[1, 1, LargeRowCount, 1]; + range.ConditionalFormatting.AddAboveStdDev(); + range.ConditionalFormatting.AddBelowStdDev(); + AssertExportIsFast(range); + } + } + + [TestMethod] + public void PercentileIconSetAndDataBarOnLargeRangeShouldExportInLinearTime() + { + using (var p = new ExcelPackage()) + { + var ws = CreateSheet(p, LargeRowCount); + var range = ws.Cells[1, 1, LargeRowCount, 1]; + var iconSet = range.ConditionalFormatting.AddThreeIconSet(eExcelconditionalFormatting3IconsSetType.Arrows); + iconSet.Icon2.Type = eExcelConditionalFormattingValueObjectType.Percentile; + iconSet.Icon2.Value = 33; + iconSet.Icon3.Type = eExcelConditionalFormattingValueObjectType.Percentile; + iconSet.Icon3.Value = 67; + + var dataBar = range.ConditionalFormatting.AddDatabar(Color.Blue); + dataBar.LowValue.Type = eExcelConditionalFormattingValueObjectType.Percentile; + dataBar.LowValue.Value = 10; + dataBar.HighValue.Type = eExcelConditionalFormattingValueObjectType.Percentile; + dataBar.HighValue.Value = 90; + AssertExportIsFast(range); + } + } + + [TestMethod] + public void RulesOverFullSheetShouldNotWalkEmptyCells() + { + using (var p = new ExcelPackage()) + { + var ws = p.Workbook.Worksheets.Add("Sheet1"); + ws.Cells["A1"].Value = 1; + ws.Cells["A2"].Value = 1; + ws.Cells["B3"].Value = 5; + const string fullSheet = "A1:XFD1048576"; + ws.ConditionalFormatting.AddDuplicateValues(fullSheet); + ws.ConditionalFormatting.AddUniqueValues(fullSheet); + ws.ConditionalFormatting.AddTop(fullSheet); + ws.ConditionalFormatting.AddTwoColorScale(fullSheet); + ws.ConditionalFormatting.AddThreeColorScale(fullSheet); + ws.ConditionalFormatting.AddThreeIconSet(fullSheet, eExcelconditionalFormatting3IconsSetType.Arrows); + ws.ConditionalFormatting.AddDatabar(fullSheet, Color.Blue); + + AssertExportIsFast(ws.Cells["A1:B3"]); + } + } + + [TestMethod] + public void DuplicateAndUniqueValuesShouldMatchExpectedCells() + { + using (var p = new ExcelPackage()) + { + var ws = p.Workbook.Worksheets.Add("Sheet1"); + ws.Cells["A1"].Value = "a"; + ws.Cells["A2"].Value = "A"; + ws.Cells["A3"].Value = "b"; + ws.Cells["A4"].Value = 1; + ws.Cells["A5"].Value = 2; + ws.Cells["A6"].Value = 2; + + var dup = (ExcelConditionalFormattingDuplicateValues)ws.ConditionalFormatting.AddDuplicateValues("A1:A6"); + var uni = (ExcelConditionalFormattingUniqueValues)ws.ConditionalFormatting.AddUniqueValues("A1:A6"); + + var expectedDup = new[] { true, true, false, false, true, true }; + var expectedUnique = new[] { true, true, true, true, false, false }; //Unique compares the values case sensitive. + for (int r = 1; r <= 6; r++) + { + Assert.AreEqual(expectedDup[r - 1], dup.ShouldApplyToCell(new ExcelAddress(r, 1, r, 1)), $"Duplicate A{r}"); + Assert.AreEqual(expectedUnique[r - 1], uni.ShouldApplyToCell(new ExcelAddress(r, 1, r, 1)), $"Unique A{r}"); + } + ws.ConditionalFormatting.ClearTempExportCacheForAllCFs(); + } + } + + [TestMethod] + public void CacheShouldBeClearedBetweenExports() + { + using (var p = new ExcelPackage()) + { + var ws = p.Workbook.Worksheets.Add("Sheet1"); + ws.Cells["A1"].Value = 1; + ws.Cells["A2"].Value = 2; + ws.Cells["A3"].Value = 3; + var range = ws.Cells["A1:A3"]; + range.ConditionalFormatting.AddDuplicateValues().Style.Fill.BackgroundColor.SetColor(Color.Red); + var first = range.CreateHtmlExporter().GetHtmlString(); + + ws.Cells["A3"].Value = 2; + var second = range.CreateHtmlExporter().GetHtmlString(); + + Assert.AreNotEqual(first, second); + } + } + } +}