Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -330,16 +330,41 @@ internal List<ExcelConditionalFormattingIconDataBarValue> GetCustomIconList(bool
return customIconList;
}

double[] _sortedPercentileValues = null;

/// <summary>
/// Number of cached values less than <paramref name="value"/>.
/// The values are sorted once per export instead of scanning the cache for every cell.
/// </summary>
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
var range = _ws.Cells[address.Address];
var cellValue = range.Value;
if(cellValue.IsNumeric() && cellValue != null)
{
if (cellValueCache.Count == 0)
if (_cellValueCacheUpdated == false)
{
UpdateCellValueCache(false, true);
_sortedPercentileValues = null;
}

double percentile = -1d;
Expand All @@ -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;
}
Expand Down
93 changes: 93 additions & 0 deletions src/EPPlus/ConditionalFormatting/Rules/CFRangeValues.cs
Original file line number Diff line number Diff line change
@@ -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
{
/// <summary>
/// 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.
/// </summary>
internal static class CFRangeValues
{
/// <summary>
/// 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.
/// </summary>
internal static List<object> GetValues(ExcelWorksheet ws, ExcelAddressBase address)
{
var result = new List<object>();
var cells = new List<KeyValuePair<long, object>>();
foreach (var a in address.GetAllAddresses())
{
cells.Clear();
var e = new CellStoreEnumerator<ExcelValue>(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, object>(((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;
}

/// <summary>
/// Total number of cells in the address, including empty cells. Cells covered by more than one sub-address are counted once per sub-address.
/// </summary>
internal static long GetCellCount(ExcelAddressBase address)
{
long count = 0;
foreach (var a in address.GetAllAddresses())
{
count += (long)a.Rows * a.Columns;
}
return count;
}

/// <summary>
/// Returns the number of items in the sorted array that are less than <paramref name="value"/>, using <see cref="double.CompareTo(double)"/> ordering (NaN sorts first).
/// </summary>
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;
}
}
}
45 changes: 20 additions & 25 deletions src/EPPlus/ConditionalFormatting/Rules/CachingCF.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,50 +48,45 @@ internal override ExcelConditionalFormattingRule Clone(ExcelWorksheet newWs = nu
}

protected List<object> cellValueCache = new List<object>();
/// <summary>
/// True when <see cref="cellValueCache"/> has been filled for the current export.
/// </summary>
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;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -42,15 +42,25 @@ 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)
{
if(address != null && _ws.Cells[address.Address].Value != null)
{
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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,26 @@ internal override bool ShouldApplyToCell(ExcelAddress address)
return false;
}

double? _cachedMaximum = null;
double? _cachedMinimum = null;

/// <summary>
/// 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.
/// </summary>
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];
Expand All @@ -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)
{
Expand Down Expand Up @@ -440,6 +460,8 @@ internal override void RemoveTempExportData()
base.RemoveTempExportData();
highest = double.NaN;
lowest = double.NaN;
_cachedMaximum = null;
_cachedMinimum = null;
}

//internal bool GetHasNegativeBar()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,23 +40,23 @@ internal ExcelConditionalFormattingDuplicateValues(
{
}

//HashSet<string> duplicates = new HashSet<string>();
IEnumerable<string> duplicates;
HashSet<string> 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<string>(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;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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)
{
Expand Down
Loading
Loading