2013-05-30 87 views
0

我使用開放源代碼EPPlus庫,它允許您讀取Excel等電子表格文件。現在,我有一個Excel文件,但我想在查看單元格的值之前檢查單元格的Background Color。但是,我不知道用什麼enum。以下是我的示例代碼如下:使用EPPlus庫檢查Excel文件的背景顏色

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

      } 

有什麼建議嗎?

回答

0

我得到了我自己的問題的答案:-)我發現BackgroundColor有一個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(); 
     } 

而且在function返回的十六進制值:

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

函數工作,但有一個更簡單的方法來做到這一點。只需使用Color.Yellow.ToArgb()。ToString(「X」)'。它是完全相同的輸出。如果您需要更多便利,請將其作爲擴展方法。 –