Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access worksheets in EPPlus?

Tags:

I'm using the 3.1 release of EPPlus library to try to access a worksheet in an Excel file. When I try either of the following methods I get a System.ArgumentException : An item with the same key has already been added.

using (ExcelPackage package = new ExcelPackage(new FileInfo(sourceFilePath)))
{
   var worksheet = package.Workbook.Worksheets[0];

   // OR

   foreach (var excelWorksheet in package.Workbook.Worksheets)
   ...
}

Exception Stack:

System.ArgumentException : An item with the same key has already been added.
   at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
   at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
   at System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value)
   at OfficeOpenXml.ExcelNamedRangeCollection.Add(String Name, ExcelRangeBase Range)
   at OfficeOpenXml.ExcelWorkbook.GetDefinedNames()
   at OfficeOpenXml.ExcelPackage.get_Workbook()

This seems like very basic functionality to have be so broken.. am I doing something wrong?

like image 334
Shane Courtrille Avatar asked Nov 26 '12 15:11

Shane Courtrille


1 Answers

I believe that excel does worksheets from index 1 not index 0

 var worksheet = package.Workbook.Worksheets[0]; 

should be

var worksheet = package.Workbook.Worksheets[1];

to read the first worksheet.

like image 128
Pete Avatar answered Nov 04 '22 17:11

Pete