2017-09-13 777 views
1

我試圖驗證一行中的單元格不是null。如果是null,我想將單元格的背景顏色更改爲紅色。閱讀如何做到這一點後,我想出了下面的代碼:無法更改單元格背景顏色,EPPlus在C#

public int verifyImportFile(FileUpload fup) 
    { 
     int status = 0; 
     //check if there is actually a file being uploaded 
     if (fup.HasFile) 
     { 
      //load the uploaded file into the memorystream 
      using (MemoryStream stream = new MemoryStream(fup.FileBytes)) 
      //Lets the server know to use the excel package 
      using (ExcelPackage xlPackage = new ExcelPackage(stream)) 
      { 
       //Gets the first worksheet in the workbook 
       ExcelWorksheet worksheet = xlPackage.Workbook.Worksheets[1]; 
       //Gets the row count 
       var rowCnt = worksheet.Dimension.End.Row; 
       //Gets the column count 
       var colCnt = worksheet.Dimension.End.Column; 
       //Beginning the loop for data gathering 
       for (int i = 2; i < rowCnt; i++) //Starts on 2 because excel starts at 1, and line 1 is headers 
       { 
        //If there is no value in column 3, proceed 
        if (worksheet.Cells[i, 3].Value == null) 
        { 
         worksheet.Cells[i, 3].Style.Fill.PatternType = ExcelFillStyle.Solid; 
         worksheet.Cells[i,3].Style.Fill.BackgroundColor.SetColor(Color.Red); 
         status = 1; 
        }       
       } 
       xlPackage.Save(); 
      }    
     } 
     return status; 
    } 

我從測試所知道的是,如果一個價值被發現,它進入if語句來檢查。它似乎正在運行代碼來更改背景顏色。在循環遍歷整個Excel表後,變量狀態確實變爲1並顯示在彈出窗口中。 從我對如何做到這一點的理解,它運行正常,但背景顏色保持白色。

+0

如果你只是創建一個簡單的方法,顏色單元格A1紅色,它工作嗎? – silkfire

+0

@silkfire剛做出改變。它運行代碼,但仍然不會改變顏色 – TGills

+0

嘗試尋求他們的支持論壇上的幫助也許? – silkfire

回答

0

您的代碼是正確的,只要設置背景顏色假設它被擊中已確認。

但你怎麼實際上保存文件?一旦加載到MemoryStream,與原始字節數組的連接就會被切斷。你需要做一個SaveAs()GetAsByteArray()調用是這樣的:

xlPackage.SaveAs(new FileInfo(@"c:\temp\myFile.xls")); 

調用Save()剛剛寫入的MemoryStream。

+0

你知道得越多......謝謝! – TGills

0

希望這有效。 worksheet.Cells[i, 3].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red)

相關問題