How can i fill cells A1: A5 with color using C #?

I have the following code:

Excel.Range chartRange;
chartRange = xlWorkSheet.get_Range("A3", "R3");

      

I want to fill this range of cells with color. I've already tried:

System.Drawing.Color = "yellow"

      

but it throws an exception that an object reference is required.

How can I fix my code to fill these cells with color?

+1


source to share


3 answers


Try the following:



chartRange.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Yellow);

      

+9


source


The problem with your code shown above is that you cannot assign the string value "Yellow" to the type System.Drawing.Color

. Instead, the standard colors are displayed as readable properties that can be accessed through the structure Color

. See the documentation for a complete list .

Excel Intelligence makes things a little trickier because you need to convert these color values ​​to OLE colors. You do it with a method ColorTranslator.ToOle

.

So, for example, you need to add the following line to your source code:



Excel.Range chartRange;
chartRange = xlWorkSheet.get_Range("A3", "R3");
chartRange.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Yellow);

      

See also this hands- on article on MSDN for more information .

+5


source


You are directly assigning color to a worksheet variable that Excel interface cannot understand.

So, you need to convert these color values ​​to OLE values ​​using the colorTranslator.ToOle method , or use the Excel coloring method. Both methods are provided.

xlWorkSheet.get_Range(xlWorkSheet.Cells[2, 2], xlWorkSheet.Cells[2, 4]).Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Green);

      

yet

xlWorkSheet.get_Range(xlWorkSheet.Cells[2, 3], xlWorkSheet.Cells[2, 3]).Interior.Color = Excel.XlRgbColor.rgbRed;

      

Here xlWorksheet is an excel Worksheet object.

get_Range takes 2 variables one starting cell and the other one ending cell.

therefore, if you supply both values, then only one cell will be selected.

xlWorkSheet.cells [row, column] is used to specify a cell.

System.Drawing.ColorTranslator.ToOle (SystemDrawing.Color.Green) is used to define the color in OLE format.

Excel.XlRgbColor.rgbRed is a great way to colorize cells This method gives you access to a lot of colors that can be found here color list

0


source







All Articles