如何在C#中将Excel.Range.Interior.Color转换为System.Drawing.Color?

7 c# excel

我有一张excel表,其中一些单元格有一些背景颜色.我需要在HTML代码中使用这种颜色,因此我想将Excel.Range.Interior.Color转换为RGB格式或System.Drawing.Color.

在这之后,我将使用System.Drawing.ColorTranslator.ToHtml(System.Drawing.Color)来获取要在html标签中使用的颜色.

我尝试过以下方法:

Excel.Range r = (Excel.Range)m_objRange[2, 2];
System.ComponentModel.TypeConverter converter = System.ComponentModel.TypeDescriptor.GetConverter(r.Interior.Color);
               MessageBox.Show(""+converter.ConvertTo(r.Interior.Color,typeof(System.Drawing.Color)));
Run Code Online (Sandbox Code Playgroud)

但我得到一个错误,我无法将System.Double转换为System.Drawing.Color

yoy*_*sef 14

让ColorTranslator为您完成工作要容易得多:

System.Drawing.Color col = System.Drawing.ColorTranslator.FromOle((int) r.Interior.Color);
Run Code Online (Sandbox Code Playgroud)

当您在Visual Studio中使用自动生成的代理对象(而不是常规的Interop项目)编写Excel项目时,您需要将r.Interior.Color转换为double,然后返回到int:

System.Drawing.Color col = System.Drawing.ColorTranslator.FromOle((int)((double) r.Interior.Color));
Run Code Online (Sandbox Code Playgroud)


jga*_*ant 4

Excel.Range.Interior.Color 返回的值是颜色的长整型值。

例子

'#000000等于0

'#FFFFFF 等于 16777215

您需要将十进制值转换为十六进制。从那里,很容易转换为 RGB。(分成 2 个八位位组,然后转换回十进制):)