如何使用 Excel COM Interop 以编程方式对包含数字的单元格区域应用条件格式?

Yon*_*ona 3 c# excel conditional-formatting

在 MS Excel 中,您可以选择一个单元格范围并在此范围上应用条件格式。有没有一种方法可以在 C# 中使用 来实现这一点Microsoft.Office.Interop.Excel

给定一系列包含数字的单元格,我需要应用Red-Yellow-Green color scale. 如果没有方法,有谁知道根据数字范围和单元格中的数字应用颜色的公式吗?

Excel 中的命令

输出

Abe*_*bel 5

根据Don 的评论,Microsoft 在 C# 和 VB 中提供了一个完整的示例,说明如何在 Excel 中使用以下命令进行条件格式设置Microsoft.Office.Interop.Excel:在给定范围内、使用.FormatConditions.AddColorScale()颜色或.FormatConditions.AddIconSetCondition()图标集条件格式设置

根据 SO 指南,如果链接消失,以下是应用颜色格式的本质(取自该链接):

// 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;
Run Code Online (Sandbox Code Playgroud)

重要提示:通过 COM 与 Excel 使用的颜色值要求颜色符合00BBGGRR格式(第一个字节始终为零)。默认情况下,.NET在类AARRGGBB中使用System.Drawing.Color,因此不能直接使用这些颜色(作为助记符,COM 颜色按字母顺序排列:蓝色、绿色、红色)。

与 .NET 中的任何 Excel 互操作一样,您需要引用 Excel 12.0 对象库并导入Microsoft.Office.Interop.Excel命名空间。