6
votes

I am trying to get background color of some cells in an Excel sheet in C#. I am using follwoing code for it:

Excel.Range r = (Excel.Range)m_objRange[i, j];                                  
int decValue = int.Parse(r.Interior.Color.ToString());
string hexValue = decValue.ToString("X");

So i get the long decimal value and then i convert into hex to use it into an html code. Now i have a problem in getting the right colors. For example:

Case 1.

Actual Color-Red

Returned Decimal value-255

Corresponing Hex value- FF (or 0000FF)

Corresponing color i got- Blue

Case 2.

Actual Color-Blue

Returned Decimal value-16711680

Corresponing Hex value- FF0000

Corresponing color i got- Red

Case 3.

Actual Color-Green

Returned Decimal value-32768

Corresponing Hex value- 8000

Corresponing color i got- White

Now in case 1, i guess i should interpret hex value of FF as #FF0000 to get it as red? In case 3, i should interpret hex value of 8000 as #008000 to get is a green?

Is there a way where i can directly get six digit hex value which would be exactly the color that i want? I am getting wrong decimal values or I am not converting decimal into hex properly?

And what is happening in Case 2? Here i am getting six digit hex value but it is completely wrong. FF0000 is clearly red and not blue.

2

2 Answers

10
votes

This work for me:


int colorNumber = System.Convert.ToInt32(((Range) worksheet.Cells[rowNumber,columnNumber]).Interior.Color);
Color color = System.Drawing.ColorTranslator.FromOle(colorNumber);
1
votes

try this:

System.Color col = System.Drawing.ColorTranslator.FromOle((int) r.Interior.Color);
string htmlCol = System.Drawing.ColorTranslator.ToHtml(col);

(warning, I didn't test this)