Search code examples
c#excelepplus

Updating the excelsheet using EPPlus in c#


I have a excel file which contains sheet named Data. This sheet already contains few data. I need to open this file and add more data in it. I have tried searching about this but everyone is just creating new sheets in their workbook. I need to update the current sheet. Below is my code:

MemoryStream ms = new MemoryStream();
using (FileStream fs = File.OpenRead(@"Path\File.xlsx")
using (ExcelPackage excelPackage = new ExcelPackage(fs))
{
  ExcelWorkbook excelWorkBook = excelPackage.Workbook;
  ExcelWorksheet excelWorksheet = excelWorkBook.Worksheets.First();
  excelWorksheet.Cells[1, 1].Value = "Test";
  excelWorksheet.Cells[3, 2].Value = "Test2";
  excelWorksheet.Cells[3, 3].Value = "Test3";

  excelPackage.SaveAs(ms); 
} 

but it didnt update the sheet. I do not what I am doing wrong. Can anyone help me please. Thanks


Solution

  • You are doing this:

    1. Create a MemoryStream object in memory to store binary data.
    2. Open file and read it into the MemoryStream object.
    3. Create an ExcelPackage object based on the data in the MemoryStream object.
    4. Make changes to the spreadsheet.
    5. Save changes back to the MemoryStream object.

    That's why the spreadsheet file does not get updated.

    Use FileInfo and open the file directly with ExcelPackage:

    // using System.IO;
    
    FileInfo file = new FileInfo(@"Path\File.xlsx");
    using (ExcelPackage excelPackage = new ExcelPackage(file))
    {
      ExcelWorkbook excelWorkBook = excelPackage.Workbook;
      ExcelWorksheet excelWorksheet = excelWorkBook.Worksheets.First();
      excelWorksheet.Cells[1, 1].Value = "Test";
      excelWorksheet.Cells[3, 2].Value = "Test2";
      excelWorksheet.Cells[3, 3].Value = "Test3";
    
      excelPackage.Save();
    }