As per the comment by Don, Microsoft provides a full example in C# and VB on how to do conditional formatting in Excel using Microsoft.Office.Interop.Excel
: on a given range, use .FormatConditions.AddColorScale()
for color, or .FormatConditions.AddIconSetCondition()
for icon set conditional formatting
As per SO guidelines, in case the link goes away, here's the essence of applying color formatting, as taken from that link:
// Fill cells A1:A10 with sample data.
targetSheet.get_Range("A1",
paramMissing).set_Value(XlRangeValueDataType.xlRangeValueDefault, 1);
targetSheet.get_Range("A2", paramMissing).set_Value(XlRangeValueDataType.xlRangeValueDefault, 2);
targetSheet.get_Range("A1:A2",
paramMissing).AutoFill(targetSheet.get_Range("A1:A10", paramMissing), XlAutoFillType.xlFillSeries);
// Create a two-color ColorScale object for the created sample data
// range.
cfColorScale = (ColorScale)(targetSheet.get_Range("A1:A10",
Type.Missing).FormatConditions.AddColorScale(2));
// Set the minimum threshold to red (0x000000FF) and maximum threshold
// to blue (0x00FF0000). Values are in 00BBGGRR format.
cfColorScale.ColorScaleCriteria[1].FormatColor.Color = 0x000000FF;
cfColorScale.ColorScaleCriteria[2].FormatColor.Color = 0x00FF0000;
Important: Color values used through COM with Excel require the color to be in 00BBGGRR
format (first byte always zero). By default, .NET uses AARRGGBB
in the System.Drawing.Color
classes, so these colors cannot be used directly (as a mnemonic, the COM colors are in alphabetic order: Blue, Green, Red).
As with any Excel interop from .NET, you need to reference the Excel 12.0 Object library and import the Microsoft.Office.Interop.Excel
namespace.