Skip to content

Conditional Formatting ‐ Priority

Mats Alm edited this page Jan 25, 2024 · 13 revisions

You can apply multiple ConditionalFormattings to a singular cell/range with Epplus.

However in some cases two different ConditionalFormattings may affect the look of the same style attribute. For example both may be trying to change the background colour of the cell. Excel and in turn Epplus resolves this with an integer called Priority where a ConditionalFormattingRule has higher priority the lower the value is. Highest possible priority is when priority = 1.

When there is no conflict on a certain attribute it will apply the only attribute that can be found even if its from a ConditionalFormatting with lower priority.

For example in this sample, the highPriority.BackgroundColor will be visible in excel due to its priority but 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


Back to Conditional Formatting

EPPlus wiki

Versions

Worksheet & Ranges

Styling

Import/Export data

Formulas and filters

Charts & Drawing objects

Tables & Pivot Tables

VBA & Protection

Clone this wiki locally