Search code examples
c#.netconditional-formattingclosedxml

How do you get ClosedXML to use conditional formatting with formulas?


According to the documentation you can add conditional formatting to a cell using the syntax:

.AddConditionalFormat().WhenEquals("=B1")

So I tried this:

cell.AddConditionalFormat().WhenEquals("=F5=0")
    .Fill.SetBackgroundColor(XLColor.FromHtml("#f00"));

However, whenever I try this, load the spreadsheet into Excel, and look at the conditional formatting for the cell, it seems to have changed it to a simple 'cell value equals' type, rather than a formula type. So I see this:

enter image description here

but what I want to see is this:

enter image description here

What am I missing!?


Solution

  • After fruitlessly digging in Google for hours, I gave up and went back to basics. I eventually noticed a method called WhenIsTrue(), which accepts a formula!

    So, in case anyone else gets here looking for this (this question seems to be the second best ranking answer in Google for 'conditional formatting closedxml'), this is the answer.

    cell.AddConditionalFormat().WhenIsTrue("=F5=0")
        .Fill.SetBackgroundColor(XLColor.FromHtml("#f00"));