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);
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With