Home > other >  How to Get the font color of an Excel Cell in c#
How to Get the font color of an Excel Cell in c#

Time:12-06

okay, so I'm trying to get the cell's font color as the program needs to do different things biased on the font color in the cell so I made a test file

how the cells look inside excel

and I tried to access it like so:

Range thrange = ws.UsedRange.Columns["A:A", Type.Missing].Rows;
foreach (Range r in thrange)
{
   Style sy = r.Style;
   Font font = sy.Font;
   ColorFormat color = (ColorFormat)font.Color;
   Console.WriteLine("  " r.Value "  "   color.RGB);
}

I get Can not convert type 'double' to 'Microsoft.Office.Interop.Excel.ColorFormat'

I saw people saying you set the color with a drawing object so I tried changing the last two lines to:

Color color =(System.Drawing.Color)font.Color;
Console.WriteLine("  " r.Value "  "   color.ToArgb());

but that didn't work either Can not convert type 'double' to 'System.Drawing.Color'

so I thought I'd see what this double is, then set the font to a known rgb value and work out how to convert the number I get back into that. but that didn't work either. as while Console.WriteLine(" " r.Value " " r.style.font.color); didn't throw an error it still didn't give me anything useful:

 cyan 0
 pink 0
 blue 0
 red 0
 orange 0
 purple 0

I thought maybe r.style.font.colorindex but that just gave me a 1 for everything instead of a 0 I was hopping for something like

 blue 0000ff
 red ff0000

I can't use a 3rd party libraries due to the rules set out by the project owner.

So how do I get the actual color value out?

CodePudding user response:

Use the Font property of the Range not that of its Style. Then use the ColorTranslator class to convert the double value from Office to a .net Color.

foreach (Microsoft.Office.Interop.Excel.Range r in thrange)
{
    // Get Color from Font from Range directly
    int oleColor = Convert.ToInt32(r.Font.Color);
   
    // Convert to C# Color type
    System.Drawing.Color c = System.Drawing.ColorTranslator.FromOle(oleColor);

    // Output
    Console.WriteLine(r.Value   " "   c.ToString());
}
  • Related