Search code examples
c#epplus

Checking the Background Color of Excel file using EPPlus library


I am using the Open Source EPPlus library which allows you to read Spreadsheet files like Excel. Now, I have an Excel file but I want to check the Background Color of a Cell before I get the value of a cell. However, I don't know what enum to use. Here is my example code below:

            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 == whatShouldBeTheEnumHere)
                {
                  String getValue = theCell.Value.ToString();
                }

            }

Any suggestions?


Solution

  • I got the answer to my own question :-) I found out that BackgroundColor has an RGB property and that's what I used to get the value of color that I want to test. This is the code

            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();
                }
    
            }
    

    Or of course I could use a function to return the HexValue like

       if (theCell.Style.Fill.BackgroundColor.Rgb == ColorHexValue(Color.Yellow))
          {
            String getValue = theCell.Value.ToString();
          }
    

    And the the function to return the Hex Value:

       private String ColorHexValue(System.Drawing.Color C)
        {
            return C.A.ToString("X2") + C.R.ToString("X2") + C.G.ToString("X2") + C.B.ToString("X2");
        }