在 C# 中获取 Excel 单元格背景颜色的问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/957154/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Problem with getting Excel cell background colors in C#
提问by
I am trying to get background color of some cells in an Excel sheet in C#. I am using follwoing code for it:
我试图在 C# 中的 Excel 工作表中获取某些单元格的背景颜色。我正在使用以下代码:
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:
所以我得到了长十进制值,然后我将其转换为十六进制以将其用于 html 代码。现在我在获得正确的颜色方面遇到了问题。例如:
Case 1.
情况1。
Actual Color-Red
实际颜色-红色
Returned Decimal value-255
返回的十进制值 - 255
Corresponing Hex value- FF (or 0000FF)
对应的十六进制值 - FF(或 0000FF)
Corresponing color i got- Blue
我得到的对应颜色 - 蓝色
Case 2.
案例 2。
Actual Color-Blue
实际颜色-蓝色
Returned Decimal value-16711680
返回的十进制值-16711680
Corresponing Hex value- FF0000
对应的十六进制值 - FF0000
Corresponing color i got- Red
我得到的对应颜色 - 红色
Case 3.
案例 3。
Actual Color-Green
实际颜色-绿色
Returned Decimal value-32768
返回的十进制值-32768
Corresponing Hex value- 8000
对应的十六进制值 - 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?
现在在情况 1 中,我想我应该将 FF 的十六进制值解释为 #FF0000 以使其变为红色?在情况 3 中,我应该将 8000 的十六进制值解释为 #008000 以获得绿色?
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 中发生了什么?在这里,我得到了六位十六进制值,但这是完全错误的。FF0000 显然是红色而不是蓝色。
回答by yoyoyoyosef
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)
(警告,我没有测试这个)
回答by Campinho
This work for me:
这对我有用:
int colorNumber = System.Convert.ToInt32(((Range) worksheet.Cells[rowNumber,columnNumber]).Interior.Color);
Color color = System.Drawing.ColorTranslator.FromOle(colorNumber);