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

Unable to change cell background colour, EPPlus in C#

我正在尝试验证一行中的某个单元格不是 null。如果是null,我想把单元格的背景颜色改成red。在阅读了如何做到这一点之后,我想出了以下代码:

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

我从测试中知道的是,如果找到 null 值,它会进入检查 nulls 的 if 语句。似乎是 运行 更改背景颜色的代码。在它遍历整个 excel sheet 之后,变量 status 确实变为 1 并显示在弹出窗口中。 根据我对如何执行此操作的理解,它是 运行 正确但背景颜色保持白色。

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

你的代码在设置背景颜色方面是正确的,假设它被击中,已经确认。

但是您实际上是如何保存文件的?一旦加载到 MemoryStream ,与原始字节数组的连接就会被切断。您需要像这样进行 SaveAs()GetAsByteArray() 调用:

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

调用 Save() 只是写入 MemoryStream。