Click here to Skip to main content
15,906,333 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I'm trying to obtain the font color and I tried to reverse how I set the color, however I'm getting an invalid cast exception. I'm not sure what I did wrong. Here's what I have:

C#
public System.Drawing.Color GetRangeFontColor(string range)
{
    System.Drawing.Color color;

    Excel.Range workingRangeCells = excelWorksheet.get_Range(range, Type.Missing);
    color = (System.Drawing.Color) workingRangeCells.Font.Color;

    return color;
}
public void SetRangeFontColor(string range, System.Drawing.Color color)
{
    Excel.Range workingRangeCells = excelWorksheet.get_Range(range, Type.Missing);
    workingRangeCells.Font.Color = System.Drawing.ColorTranslator.ToOle(color);
    return;
}


Thank you for help! :)
Posted
Updated 28-Jul-10 5:57am
v2

Use the ColorTranslator[^] class instead of typecast. You'll have to use its FromOle[^] method in order to convert the OLE color value to GDI+ Color. :)

[UPDATE]
ColorTranslator.FromOle method requires an integer as parameter. So you'll need to convert from Range.Font.Color to int. Instead of using a typecast, try with Convert.ToInt32[^] method.

I've made a test and the following code works fine for me:
C#
Excel.Range workingRangeCells = excelWorksheet.get_Range(range, Type.Missing);
System.Drawing.Color color = System.Drawing.ColorTranslator.FromOle(Convert.ToInt32(workingRangeCells.Font.Color));

[/UPDATE]

:)
 
Share this answer
 
v4
Comments
gmhanna 28-Jul-10 11:48am    
Reason for my vote of 5
Works like a champ! -- Thank you!
Nuri Ismail 28-Jul-10 11:55am    
You're welcome! :)
Hi,

I have tried what you suggested and now I'm receiving a specified cast not valid when trying to cast workingRangeCells.Font.Color to an int. workingRangeCells.Font.Color returned an Object before I casted it. ColorTranslator.FromOle wants an (int).

color = ColorTranslator.FromOle((int) workingRangeCells.Font.Color);


Thank you,
 
Share this answer
 
Comments
Nuri Ismail 28-Jul-10 11:18am    
You should convert the Color to integer instead of casting it. I will update my answer in order to show you how.

PS: It's better to post a comment or edit your original question for such clarifications instead of posting "fake answers". This improves forum readability.

:)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900