How to add a new sheet to an exising Excel file with EPPlus?

Using EPPlus I want to add a new sheet to an Excel file but I do not want to delete the existing sheets in the file if any, and I want to insert it as the first sheet in the file. Here is what I have written for a quick test but it deletes all the existing sheets:

using (ExcelPackage p = new ExcelPackage())
{
    p.Workbook.Worksheets.Add("HubaHuba");
    p.Workbook.Worksheets.MoveToStart("HubaHuba");
    ExcelWorksheet ws = p.Workbook.Worksheets[1];
    ws.Name = "HubaHuba";

    var cell = ws.Cells[1, 1];
    cell.Value = "dfsdfsdfsd";
    cell = ws.Cells[1, 2];
    cell.Value = "347895y5 Oh";

    Byte[] bin = p.GetAsByteArray();
    File.WriteAllBytes(path,bin);
}

Upvotes: 8

Views: 25876

Answers (2)

daniele3004
daniele3004

Reputation: 13970

using (ExcelPackage excelEngine = new ExcelPackage())
{
     excelEngine.Workbook.Worksheets.Add("sheet1");
     excelEngine.Workbook.Worksheets.Add("sheet2");
     excelEngine.Workbook.Worksheets.Add("sheet3");

     String myFile= "c:\....\xx.xlsx";
     excelEngine.SaveAs();

}

When you use Add the sheet is added at the and of current file sheets.

If you want to add in a specific position use this function:

excelEngine.Workbook.Worksheets.Add("sheet0");
excelEngine.Workbook.Worksheets.MoveBefore(4, 1);

sheet0 is added at the and in 4th position and you move it in first position with the previous code.

Upvotes: 10

walther
walther

Reputation: 13598

That's because you're rewriting the file with command File.WriteAllBytes. Instead you should just call p.Save() and ExcelPackage needs to use the constructor that accepts the file path. Then it will work.

Upvotes: 4

Related Questions