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);
}
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.