Search code examples
c#excelepplus

Unable to change cell background colour, EPPlus in C#


I'm trying to verify that a cell in a row is not null. If it is null, I want to change the background colour of the cell to red. After reading how to do that, I have come up with the following code:

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

What I do know from testing is that if a null value is found, it enters the if statement that checks for nulls. It seems to be running the code to change the background colour. After it loops through the entire excel sheet, the variable status does change to 1 and is displayed in a popup. From my understanding of how to do this, it is running properly but the background colour stays white.


Solution

  • Your code is correct as far as setting the background color assuming it is being hit which have confirmed.

    But how are you actually saving out the file? Once you load to a MemoryStream the connection to the original byte array is severed. You need to do a SaveAs() or GetAsByteArray() call like this:

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

    Calling Save() just writes to the MemoryStream.