Here’s my code. Its purpose is to count the number of lines where the first column has text in it.
ExcelWorksheet sheet = null;
using (ExcelPackage pkg = new ExcelPackage(new MemoryStream(_fileBytes)))
{
sheet = pkg.Workbook.Worksheets[1];
}
int rows = sheet.Dimension.End.Row;
int count = 0;
for (int i = 1; i <= rows; ++i)
{
if (!string.IsNullOrEmpty(sheet.Cells[i, 1].Text))
++count;
}
When I just run the code outside the debugger, I get an exception at the sheet.Cells[i, 1].Text call:
Package object was closed and disposed, so cannot carry out operations
on this object or any stream opened on a part of this package.
When I step through it with the debugger, I get the same exception… UNLESS I have this in my Watch window: sheet.Cells[1, 1].Text. If I run the debugger over the code (ie. press F5), from before the sheet object is initialized, I get the exception. If I step through the code with that snipped in my Watch window, NO EXCEPTION. The code works flawlessly. The Watch window correctly shows the contents of the first cell. What gives?
You get the exception because you are trying to access the worksheet of the
ExcelPackageoutside of theusingstatement (disposes the package).By the way, you can shorten the code with Linq: