Search code examples
c#epplus

Issue writing to spreadsheet using EPPlus


I'm simply trying to edit a spreadsheet that has text already written into to change the text to be blank.

However it's not working. The method seems to do nothing.

My code is:

public static void ClearCells(string SpreadsheetFilePath)
{
    var SpreadsheetPath = new FileInfo(SpreadsheetFilePath);
    var package = new ExcelPackage(SpreadsheetPath);
    ExcelWorkbook workBook = package.Workbook;
    if (workBook != null)
    {
        if (workBook.Worksheets.Count > 0)
        {
            ExcelWorksheet currentWorksheet = workBook.Worksheets.First();
            currentWorksheet.SetValue(1, 1, "hello123");
        }
    }
}

There is no runtime error. It runs, completes and the spreadsheet is unchanged. I don't know why.


Solution

  • Just call package.Save(); after you are done editing your file.

    var SpreadsheetPath = new FileInfo(@"C:\temp\abc.xlsx");
    var package = new ExcelPackage(SpreadsheetPath);
    ExcelWorkbook workBook = package.Workbook;
    if (workBook != null)
    {
        if (workBook.Worksheets.Count > 0)
        {
            ExcelWorksheet currentWorksheet = workBook.Worksheets.First();
            currentWorksheet.SetValue(1, 1, "hello123");
        }
    }
    
    package.Save();  // <========= MISSING IN YOUR CODE