无法更改单元格背景颜色,EPPlus在C#

我试图validation一行中的单元格不为 。 如果它是空的 ,我想改变单元格的背景颜色为红色 。 读完之后,我想出了以下代码:

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

我从testing中知道的是,如果find值,它将进入检查空值的if语句。 它似乎正在运行的代码来改变背景颜色。 在循环遍历整个Excel表单后,variables状态将变为1,并显示在popup窗口中。 从我的理解如何做到这一点,它运行正常,但背景颜色保持白色。

你的代码是正确的,只要设置背景颜色假设它已被确认。

但你怎么实际上保存文件? 一旦你加载到一个MemoryStream的连接到原始字节数组被切断。 您需要执行SaveAs()GetAsByteArray()调用,如下所示:

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

调用Save()只需写入MemoryStream。

希望这可以工作。 worksheet.Cells[i, 3].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red)