我无法使用EPPLUS获取背景颜色的真实RGB值 .
我的代码只适用于在excel上设置为RGB的颜色,具有托盘颜色的单元格无法识别 .
这是代码,希望有人可以帮助我:
ExcelRangeBase c = sheet.Cells[k, j];
var wbs = sheet.Workbook.Styles;
var fill = c.Style.Fill;
string rgb = "";
if (fill.PatternType == OfficeOpenXml.Style.ExcelFillStyle.Solid)
{
rgb = !String.IsNullOrEmpty(fill.BackgroundColor.Rgb) ? fill.BackgroundColor.Rgb :
fill.PatternColor.LookupColor(fill.BackgroundColor);
}
else if (fill.PatternType != OfficeOpenXml.Style.ExcelFillStyle.None)
{
rgb = !String.IsNullOrEmpty(fill.PatternColor.Rgb) ? fill.PatternColor.Rgb :
fill.PatternColor.LookupColor(fill.PatternColor);
}
if (rgb.StartsWith("#")) rgb.Replace("#", "");
rgb = rgb.Trim();
// Removes ALPHA from ARGB
if (rgb.Length == 8 || rgb.Length == 5) rgb = rgb.Substring(2);
else if (rgb.Length > 8) rgb = rgb.Substring(rgb.Length - 6);
if (!rgb.StartsWith("#")) rgb = "#" + rgb;
string bg = "";
// I got this validation because most times lookupColor returns FF000;
if (rgb != null && rgb != "" && rgb != "#000" && rgb != "#000000")
{
bg = "background: " + rgb + "; ";
}
2 回答
如果您在Excel颜色下拉列表中选择了'Theme colors'而不是'Standard colors',或者从颜色选择器中选择了其中一个,它似乎不起作用,如此问题的答案中所述:EPPlus Excel Change cell color
似乎不支持主题 - EPPlus FAQ
事实证明,这是如何
LookupColor
在EPPlus中工作的一个怪癖 . 具体来说,颜色的格式为returned in this case is AA,分别为R,G和B的两个字符和一个恒定长度序列,指定灰色阴影 . 但是,如果你看一下代码,你可能会得到一些非常奇怪的颜色(即它是's probably bugged). That' s因为使用的常量长度可以是1到3个字符,上限为0x0200
.例如,
((int)(decimal.Round(-1M * -512))).ToString("X")
返回"200"
,通过推断,将返回#FF200200200
. 但是,如果没有提交修补程序来改变处理方式,那么执行此操作的方法可能是相信这是可以为通道返回的上限,然后在0-> FF之间进行缩放 .有关此方法,请参阅下文 . 请注意,如果在EPPlus本身中已经修复了这个问题,则下面的内容会错误地缩放(因为实际上限将是
FF
,而不是0x0200
) .