Epplus获得正确的细胞背景RGB颜色

我无法使用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 + "; "; } 

如果您在Excel颜色下拉菜单中select了一种“主题颜色”,而不是“标准颜色”或从颜色select器中select其中一种,则此function似乎不起作用,如此处所述问题的答案中所述: EPPlus Excel更改单元格颜色

看来主题不支持 – EPPlus FAQ

库不支持什么(这些是最明显的function)? *主题

事实certificate,这是LookupColor如何在LookupColor工作的一个怪癖。 具体而言, 在这种情况下返回的颜色的格式是AA {R} {G} {B} ,其具有分别针对R,G和B中的每一个的alpha和一个恒定长度序列的两个字符,指定灰度阴影。 然而,如果你看看代码,你可能会得到一些非常奇怪的颜色(即它可能被窃听)。 这是因为使用的恒定长度范围为1到3个字符,上限为0x0200

例如, ((int)(decimal.Round(-1M * -512))).ToString("X")返回"200" ,通过推断,将返回#FF200200200 。 然而,在提交补丁来改变处理方式的时候,可能的办法就是相信这可以为频道返回的上限,然后在0-> FF之间进行缩放。

有关这样做的方法,请参阅下文。 请注意,如果EPPlus本身已经修复了这个问题,那么下面的内容会错误地进行缩放(因为实际上限将是FF ,而不是0x0200 )。

 private string EPPLookupColorFixed(ExcelColor sourceColor) { var lookupColor = sourceColor.LookupColor(); const int maxLookup = 63; bool isFromTable = (0 <= sourceColor.Indexed) && (maxLookup > sourceColor.Indexed); bool isFromRGB = (null != sourceColor.Rgb && 0 < sourceColor.Rgb.Length); if (isFromTable || isFromRGB) return lookupColor; // Ok, we know we entered the else block in EPP - the one // that doesn't quite behave as expected. string shortString = "0000"; switch (lookupColor.Length) { case 6: // Of the form #FF000 shortString = lookupColor.Substring(3, 1).PadLeft(4, '0'); break; case 9: // Of the form #FFAAAAAA shortString = lookupColor.Substring(3, 2).PadLeft(4, '0'); break; case 12: // Of the form #FF200200200 shortString = lookupColor.Substring(3, 3).PadLeft(4, '0'); break; } var actualValue = short.Parse(shortString, System.Globalization.NumberStyles.HexNumber); var percent = ((double)actualValue) / 0x200d; var byteValue = (byte)Math.Round(percent * 0xFF,0); var byteText = byteValue.ToString("X"); byteText = byteText.Length == 2 ? byteText : byteText.PadLeft(2, '0'); return $"{lookupColor.Substring(0, 3)}{byteText}{byteText}{byteText}"; }