以编程方式在Excel 2007中添加条件格式

Raj*_*esh 2 c# excel excel-2007 excel-formula

我想以编程方式使用excel 2007的条件格式化功能.我有以下场景.

我有6列数字

A   B  C  D  E  F
100 25 25 15 20 50
....
Run Code Online (Sandbox Code Playgroud)

if (C1/A1)*100 >= B1我必须将它染成红色.同样的规则适用于D1,E1,F1列.

我在excel 2007中看到了条件格式化功能.但是我想要一些关于如何在c#代码中实现它的指针.

Sid*_*and 8

我会假设您很乐意使用Interop,因为您没有另外说过.这是我用来在Excel中设置条件格式的方法.它假设您已经Worksheet在一个名为的变量中引用了您的引用xlWorksheet.

// Create a FormatCondition and add it to the specified range of cells, using the
// passed-in condition and cell colour

Excel.Range range = xlWorksheet.get_Range("C1", "C1");
Excel.FormatConditions fcs = range.FormatConditions;
Excel.FormatCondition fc = (Excel.FormatCondition)fcs.Add
    (Excel.XlFormatConditionType.xlExpression, Type.Missing, "=IF($C$1/$A$1)*100 >= $B$1");
Excel.Interior interior = fc.Interior;
interior.Color = ColorTranslator.ToOle(Color.Red);
interior = null;
fc = null;
fcs = null;
range = null;
Run Code Online (Sandbox Code Playgroud)

我已经猜到了你的用途,但你可以摆弄它以获得正确的公式和单元格引用.