Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excel Interop Conditional Formatting

I've just spotted the following page: Setting Conditional Formatting in Excel 2007 which is very similar to something I'd like to do, but I can't seem to find appropriate functions to do something slightly different.

I'm wondering if anyone knows a way to apply conditional formatting to a range, based upon a set of textual values. E.g. I want to say:

If you see "InvalidValue1" OR "InvalidValue2" Highlight RED else if you see "WARNING" Highlight YELLOW

I have a whole range of invalid values, and possibly warning values. I also need to do this on a column by column basis for very large datasets, so where possible I'd like to use built in Excel features to highlight errors within the range.

Does anyone know if this is at all possible?

like image 504
Ian Avatar asked Jun 09 '09 10:06

Ian


2 Answers

I believe I have managed to find a solution to the problem (although Cell selection is rather bizarre and I haven't quite sorted that out yet. e.g. my formula uses A1 which actually means C1 because of the selected range).

Here is the code I used for anyone else interested:

string condition = @"=OR(ERROR1, ERROR2, ERROR3)";
var cfOR = (FormatCondition)targetSheet.get_Range("C1", "C10").FormatConditions.Add(XlFormatConditionType.xlExpression, Type.Missing,condition), Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

cfOR.Interior.Color = 0x000000FF;
cfOR.Font.Bold = true;
cfOR.Font.Color = 0x00FFFFFF;

Note that the FormatConditions.Add() method has a different signature for different versions of the Excel interop.

like image 169
Ian Avatar answered Nov 10 '22 01:11

Ian


 using Excel = Microsoft.Office.Interop.Excel;
 ...
 object mis = Type.Missing;

 Excel.FormatCondition cond =
    (Excel.FormatCondition)range.FormatConditions.Add(Excel.XlFormatConditionType.xlCellValue,
    Excel.XlFormatConditionOperator.xlEqual, "1",
    mis, mis, mis, mis, mis);
    cond.Interior.PatternColorIndex = Excel.Constants.xlAutomatic;
    cond.Interior.TintAndShade = 0;
    cond.Interior.Color = ColorTranslator.ToWin32(Color.White);
    cond.StopIfTrue = false;
like image 35
hojjat pakzad Avatar answered Nov 10 '22 01:11

hojjat pakzad