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

问题描述 投票:2回答:1

我想以编程方式使用excel 2007的条件格式设置功能。我有以下情况。

我有6列数字

A   B  C  D  E  F
100 25 25 15 20 50
....

if (C1/A1)*100 >= B1我必须将其着色为红色。相同的规则适用于D1,E1,F1列。

我在excel 2007中看到了条件格式设置功能。但是我想要一些有关如何在C#代码中实现它的指针。

c# excel excel-2007 excel-formula
1个回答
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;

我对您的预期用途有所猜测,但是您可以摆弄它以使公式和单元格引用正确。

© www.soinside.com 2019 - 2024. All rights reserved.