Skip to content

Conditional Formatting ‐ Priority

OssianEPPlus edited this page Aug 21, 2023 · 13 revisions

As of Epplus 7.0 you can apply multiple ConditionalFormattings to a singular cell/range with Epplus.

However in some cases two different ConditionalFormattings may affected the look of the same aspect. For example both may be trying to change the background colour of the cell but if there is no conflict it will apply that aspect to the cell/range. Excel and in turn Epplus resolves this with an integer called Priority where a ConditionalFormattingRule has higher priority the lower the value is and 1 is the lowest possible number.

For example in this sample, the highPriority.BackgroundColor will be visible in excel due to its priority but the LowPriority will be making the text italicized. Since highPriority has no Style.Font value.

using (var pck = new ExcelPackage())
{
    var sheet = pck.Workbook.Worksheets.Add("prioritySheet");

    var lowPriority = sheet.ConditionalFormatting.AddBeginsWith(new ExcelAddress("A1"));

    lowPriority.Priority = 500;

    lowPriority.Text = "D";
                
    lowPriority.Style.Fill.BackgroundColor.Color = Color.DarkRed;
    lowPriority.Style.Font.Italic = true;

    var highPriority = sheet.ConditionalFormatting.AddEndsWith(new ExcelAddress("A1"));

    highPriority.Text = "r";
    highPriority.Priority = 2;

    highPriority.Style.Fill.BackgroundColor.Color = Color.DarkBlue;
    highPriority.Style.Font.Color.Color = Color.White;

    sheet.Cells["A1"].Value = "Danger";
    
    //Change MYPATH to whatever directory you would like to save in. 
    //For example C:\\PriorityTest if you make a folder of that name.
    pck.SaveAs("MYPATH\\priorityTest.xlsx");
}

Expected Result:

image

EPPlus wiki

Versions

Worksheet & Ranges

Styling

Import/Export data

Formulas and filters

Charts & Drawing objects

Tables & Pivot Tables

VBA & Protection

Clone this wiki locally