This project has moved. For the latest updates, please go here.

.Count / .ToList() => NullReference Exception

Apr 8, 2011 at 10:06 AM

Hi guys,

first of all thanks for this awesome library - saved me a lot of time (used excelpackage before and epplus is way faster and easier to use).

I created a little tool to copy value from source workbooks to a targetworkbook but when I try to enumerate all the sheets in a workbook i get a NullReference:

 

using (ExcelPackage excelWorkbook = new ExcelPackage(fileExcel))
{ 
    lstTargetSheets.DataSource = excelWorkbook .Workbook.Worksheets.ToList();
}

The same happens when I try to loop over the Sheets with upper bound .Count of the worksheets. It maybe that the workbook is corrupt but Excel opens it without warning.

Any suggestions? 

 

Cheers

Max

p.s. the dirty workarround is by now :

 using (ExcelPackage excelWorkbook = new ExcelPackage(new FileInfo(dir.FullName + "\\" + selectedFile)))
            {
                List<ExcelWorksheet> sheets = new List<ExcelWorksheet>();
          
                for (int i = 0; i < 100; i++)
                {
                    try
                    {
                        sheets.Add(excelWorkbook.Workbook.Worksheets[i]);
                    }
                    catch
                    {
                    }
                }

                lstSourceSheets.DataSource = sheets;
                lstSourceSheets.DisplayMember = "Name";
                lstSourceSheets.ValueMember = "Name";
            }

Developer
Apr 8, 2011 at 12:01 PM

Hi,

pls create an issue and attach the workbook file to it.

/Mats

Apr 8, 2011 at 1:20 PM

Hey Mats,

thanks for the fast response. I apparently cant attach the workbook - it contains financial data.

Any hint how I can start ?

Thanks

Max

Developer
Apr 8, 2011 at 10:20 PM

Ok. I have tried to reproduce this error, but it works for me.

If you have any possibility to download the EPPlus source, compile it in debug mode and set a reference to it.

Maybe you could try to change your code to this:

// Worksheet index is 1-based, change 0 to 1
for
(int i = 1; i < 100; i++)
{
try
{
            sheets.Add(excelWorkbook.Workbook.Worksheets[i]);
}
catch(Exception e)
{
        throw new Exception("Exception occurred at index " + i, e);
}

Then hopefully the index of the first exception might give you a hint. The stacktrace of the inner exception might also be interesting.