如何在C#中获取Excel单元格的字体颜色

nzrxty8p  于 2022-12-05  发布在  C#
关注(0)|答案(1)|浏览(673)

好的,我试着得到单元格的字体颜色,因为程序需要根据单元格中的字体颜色做不同的事情,所以我做了一个测试文件

我试着这样访问它:

Range thrange = ws.UsedRange.Columns["A:A", Type.Missing].Rows;
foreach (Range r in thrange)
{
   Style sy = r.Style;
   Font font = sy.Font;
   ColorFormat color = (ColorFormat)font.Color;
   Console.WriteLine("  "+r.Value+"  " + color.RGB);
}

我得到Can not convert type 'double' to 'Microsoft.Office.Interop.Excel.ColorFormat'
我看到人们说你用一个绘图对象设置颜色,所以我试着把最后两行改成:

Color color =(System.Drawing.Color)font.Color;
Console.WriteLine("  "+r.Value+"  " + color.ToArgb());

但那也不管用Can not convert type 'double' to 'System.Drawing.Color'
所以我想看看这个double是什么,然后将字体设置为已知的rgb值,并找出如何将得到的数字转换回该值。但这也不起作用。因为虽然Console.WriteLine(" "+r.Value+" "+r.style.font.color);没有抛出错误,但它仍然没有给予我任何有用的信息:

cyan 0
 pink 0
 blue 0
 red 0
 orange 0
 purple 0

我想也许是r.style.font.colorindex,但这只是给了我一个1的一切,而不是一个0,我跳着像这样的东西

blue 0000ff
 red ff0000

由于项目所有者规定的规则,我不能使用第三方库。
那么我如何得到实际的颜色值呢?

7tofc5zh

7tofc5zh1#

使用RangeFont属性,而不是其StyleFont属性。然后使用ColorTranslator类将双精度值value从Office转换为.net Color

foreach (Microsoft.Office.Interop.Excel.Range r in thrange)
{
    // Get Color from Font from Range directly
    int oleColor = Convert.ToInt32(r.Font.Color);
   
    // Convert to C# Color type
    System.Drawing.Color c = System.Drawing.ColorTranslator.FromOle(oleColor);

    // Output
    Console.WriteLine(r.Value + " " + c.ToString());
}

相关问题