W要检查单元格的背景色是否为黄色,并且是否要完全具有背景色 ...
workSheet.Cells[rCnt, 1].Style.Fill.BackgroundColor.Rgb ==
接下来是什么?
答案 0 :(得分:0)
背景色具有 RGB 属性,您可以使用它来获取所需的颜色值。这是代码
using (var package = new ExcelPackage(excelFile))
{
ExcelWorkbook workbook = package.Workbook;
ExcelWorksheet currentWorksheet = workbook.Worksheets.First();
ExcelRange theCell = currentWorksheet.Cells[8, 1];
if (theCell.Style.Fill.BackgroundColor.Rgb == Color.Yellow.A.ToString("X2") + Color.Yellow.R.ToString("X2") + Color.Yellow.G.ToString("X2") + Color.Yellow.B.ToString("X2"))
{
String getValue = theCell.Value.ToString();
}
}
,或者您可以使用函数来返回 HexValue ,例如
if (theCell.Style.Fill.BackgroundColor.Rgb == ColorHexValue(Color.Yellow))
{
String getValue = theCell.Value.ToString();
}
函数以返回十六进制值:
private String ColorHexValue(System.Drawing.Color C)
{
return C.A.ToString("X2") + C.R.ToString("X2") + C.G.ToString("X2") + C.B.ToString("X2");
}
如果您不想使用函数,则只需使用下面的代码即可。
Color.Yellow.ToArgb().ToString("X").
这是完全相同的输出。如果您需要更多便利,请使其成为扩展方法
答案 1 :(得分:0)
不确定要怎么做,但是下面的示例将值存储在包含单元格名称和C#颜色(如果颜色为黄色)的Dictionary中。
基本电子表格数据
//open file into p
using (var p = new OfficeOpenXml.ExcelPackage(new FileInfo(@"c:\FooFolder\Foo.xlsx")))
{
ExcelWorkbook wb = p.Workbook;
ExcelWorksheet ew = wb.Worksheets.First();
//create a dictionary to store your cell colors
Dictionary<string, Color> cellColors = new Dictionary<string, Color>();
//define your rows and columns to loop through
int rowNum = ew.Dimension.Start.Row;
int rowEnd = ew.Dimension.End.Row;
int cellBegin = ew.Dimension.Start.Column;
int cellEnd = ew.Dimension.End.Column;
//loop through all of the rows
for (int y = rowNum; y<= rowEnd; y++)
{
//loop through the cells in each row
for(int x= cellBegin; x<= cellEnd; x++)
{
//get the range of the current cll
ExcelRange currentCell = ew.Cells[y, x];
//get the rgb string value of the background color
string rgb = ew.Cells[y,x].Style.Fill.BackgroundColor.Rgb;
//create variable to convert rgb color to C# color
System.Drawing.Color CurrentCellColor;
//if rgb is null then there is no background color so default to white.
if (rgb != null)
CurrentCellColor = System.Drawing.ColorTranslator.FromHtml("#" + rgb);
else
CurrentCellColor = System.Drawing.ColorTranslator.FromHtml("#FFFFFF");
//add to your dictionary if is yellow
if (rgb != null && CurrentCellColor.Equals(Color.Yellow))
cellColors.Add(currentCell.Address, CurrentCellColor);
}
}
p.Save();
}
答案 2 :(得分:0)
对于任何来到这里的人,由于我在EPPlus上玩得很开心,并且对上述答案不满意:
cell.Style.Fill.BackgroundColor.LookupColor()
返回#AARRGGBB颜色(即红色为#FFFF0000)。您感兴趣的部分可能是最后6位数字。
然后您可以将其与OP ColorHexValue函数进行匹配,或者仅将字符串与IF进行比较。