Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to delete a worksheet using EPPlus

Tags:

c#

excel

epplus

I am using this code:

ExcelPackage pck = new ExcelPackage(newFile);

var wk = pck.Workbook.Worksheets.SingleOrDefault(x => x.Name == "Content");

pck.Workbook.Worksheets.Delete(wk);

But in delete it gives me "IndexOutOfRangeException", but I am trying to delete from object, I have tried to delete by index "1", I just have two worksheets, and the same exception. The file and worksheet is not null, but when I execute delete in anyway I receive the "IndexOutOfRangeException".

What's happening?

Note: I have created this worksheet from ExcelPackage too and now i want delete it.

like image 638
c2s Avatar asked Oct 31 '25 22:10

c2s


1 Answers

Looks like you ran into some temporary bug/issue, that was already fixed. As of EpPlus 4.0.1.1, the following code works just fine:

var workbookFileInfo = new FileInfo(@"Workbook.xlsx");
using (var excelPackage = new ExcelPackage(workbookFileInfo))
{
    excelPackage.Workbook.Worksheets.Add("Worksheet1");
    excelPackage.Workbook.Worksheets.Add("Worksheet2");
    excelPackage.Save();
}
using (var excelPackage = new ExcelPackage(workbookFileInfo))
{
    var worksheet = excelPackage.Workbook.Worksheets.SingleOrDefault(x => x.Name == "Worksheet1");
    excelPackage.Workbook.Worksheets.Delete(worksheet);
    excelPackage.Save();
}

Try to update to the latest available stable version of EpPlus and if will not help you, please post additional details applicable for the latest version.

like image 70
Deilan Avatar answered Nov 03 '25 12:11

Deilan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!