2017-09-13 771 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)

相关问题