繁体   English   中英

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

[英]How to convert Excel.Range.Interior.Color to System.Drawing.Color in C#?

我有一个 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)));

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

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

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

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

System.Drawing.Color col = System.Drawing.ColorTranslator.FromOle((int)((double) r.Interior.Color));

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

例子

'#000000 等于 0

'#FFFFFF 等于 16777215

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

这是我如何使用 Function ,只需替换蓝色和红色字节。 在 vb.net 中的用法示例:

Imports Microsoft.Office.Interop

Public Class Form1

    Dim Ex_Ap As Excel.Application
    Dim Ex_Wb As Excel.Workbook
    Dim Ex_Ws As Excel.Worksheet

    Function Excel_Color_Get(ByVal i As Int32) As Color
        Static c As Color
        c = Color.FromArgb(i)
        Return Color.FromArgb(c.B, c.G, c.R)
    End Function

    Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
        Ex_Ap = New Excel.Application
        Ex_Ap.Visible = True
        Ex_Wb = Ex_Ap.Workbooks.Add
        Ex_Ws = Ex_Wb.Worksheets(1)
        Ex_Ws.Cells(7, 6).Value = "???"
        Ex_Ws.Cells(7, 6).interior.color = Color.Pink
    End Sub

    Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click
        Try
            TextBox1.BackColor = Excel_Color_Get(Ex_Ws.Cells(7, 6).interior.color)
        Catch ex As Exception
            TextBox1.Text = ex.ToString
        End Try
    End Sub

End Class

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM