简体   繁体   中英

How to programmatically apply conditional formatting on a cell range with numbers using Excel COM Interop?

In MS Excel you can select a range of cells and apply conditional formatting on this range. Is there a method that does it in C# using Microsoft.Office.Interop.Excel ?

Given a range of cells containing numbers, I need to apply Red-Yellow-Green color scale . If there isn't a method for that, does anyone know the formula for the applied colors according to the range of numbers and the number in the cell?

excel中的命令

产量

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM