简体   繁体   中英

Apply Color Scale to Excel Range in C#

I am trying to apply a color scale to an excel range. My below code snippet almost does what I want, formatting my highest cell to Red and my lowest cell to black, and scaling the cells in between, but I would like to make it apply a color scale based on the value of the cell, with a cell of value 0 to be black and a cell of value 255 to be red. With the current code, that would happen only if the highest cell is exactly 255 and the lowest cell is exactly 0. Any other max and min cell values affects the color scale. How do I apply the color scale to reference those static values? Any help appreciated!

Excel.ColorScale cfColorScale = (Excel.ColorScale)(xlWorkSheet.get_Range("1:1").FormatConditions.AddColorScale(2));
        cfColorScale.ColorScaleCriteria[1].Type = Excel.XlConditionValueTypes.xlConditionValueLowestValue;
        cfColorScale.ColorScaleCriteria[1].FormatColor.Color = Color.FromArgb(0, 0, 0); // Black

        cfColorScale.ColorScaleCriteria[2].Type = Excel.XlConditionValueTypes.xlConditionValueHighestValue;
        cfColorScale.ColorScaleCriteria[2].FormatColor.Color = Color.FromArgb(255,0,0); //red

Unless I misunderstand you, I think that can be achieved by changing the range of your values from the minimum and maximum of the selected range.

Range r = xlWorkSheet.get_Range("1:1");
int min = Convert.ToInt32(wb.Application.WorksheetFunction.Min(r));
int max = Convert.ToInt32(wb.Application.WorksheetFunction.Max(r));

ColorScale cfColorScale = (ColorScale)(r.FormatConditions.AddColorScale(2));
cfColorScale.ColorScaleCriteria[1].Type = XlConditionValueTypes.xlConditionValueLowestValue;
cfColorScale.ColorScaleCriteria[1].FormatColor.Color = Color.FromArgb(min, 0, 0);

cfColorScale.ColorScaleCriteria[2].Type = XlConditionValueTypes.xlConditionValueHighestValue;
cfColorScale.ColorScaleCriteria[2].FormatColor.Color = Color.FromArgb(max, 0, 0);

This is, of course, unless you anticipate those values will change and you want it to automatically adjust -- if that's the case, then you would need to use the worksheet changed event to check.

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