Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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);
}
like image 582
ConfusedSleepyDeveloper Avatar asked Dec 26 '22 04:12

ConfusedSleepyDeveloper


2 Answers

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.

like image 90
daniele3004 Avatar answered Feb 13 '23 22:02

daniele3004


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.

like image 21
walther Avatar answered Feb 13 '23 22:02

walther