2

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

S Andrew
  • 5,592
  • 27
  • 115
  • 237

2 Answers2

14

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();
} 
Serge
  • 3,986
  • 2
  • 17
  • 37
  • Thanks. It worked. I was actually following this first answer from this [question](http://stackoverflow.com/questions/23168657/modify-excel-cell). – S Andrew Feb 27 '17 at 07:16
2

Try this

var file = new FileInfo(path);

if (file .Exists)
{
    using (ExcelPackage excelPackage = new ExcelPackage(file))
    {
            ExcelWorksheet ws = excelPackage.Workbook.Worksheets.First();
            ws.Cells[1,1].Value = "Test1";
            excelPackage.Save();              
    }    
}
Murat Gündeş
  • 852
  • 2
  • 17
  • 31
  • I get a similar situation but with a file hosted on a sharepoint site : [link](https://stackoverflow.com/questions/62117472/write-to-excel-file-hosted-on-sharepoint-2016-using-epplus-c) @Murat Gündeş : could you have a solution ? – Hollyroody Jun 01 '20 at 22:06