'myWorkbook.Workbook.Size' threw an exception of type 'System.NullReferenceException'

Dec 7, 2011 at 8:58 PM
Edited Dec 8, 2011 at 5:29 AM


'myWorkbook.Workbook.Size' threw an exception of type 'System.NullReferenceException'

When I open an .xls file containing one sheet, and modify that single sheet, and then FileStream the workbook to the filesystem, it works.

When I open an .xls with a handful of sheets (e.g. 5 sheets) the code properly iterates through the sheets and does modfications on each sheet.

In both cases, 'myWorkbook.Workbook.Size' threw an exception of type 'System.NullReferenceException'

The workbook with one sheet writes OK even with exception:  'myWorkbook.Workbook.Size' threw an exception of type 'System.NullReferenceException'

The workbook with more than one sheet does not write to FileSystem OK: 0KB / Corrupt


 Thank you,





 Code follows...

 FileStream fsRead = new FileStream(sFilename, FileMode.Open, FileAccess.Read);

 HSSFWorkbook myWorkbook = new HSSFWorkbook(fsRead, true);

 //iterate worksheets  int numSheets = myWorkbook.NumberOfSheets; for (int sheetNum = 0; sheetNum < numSheets; sheetNum++)


ISheet sheet = myWorkbook.GetSheetAt(sheetNum);



for (int rowNum=0; rowNum<sheet.LastRowNum; rowNum++)



IRow dataRow = sheet.GetRow(rowNum);

foreach (HSSFCell cell in dataRow)



cell.CellStyle.WrapText =false;





FileStream fsWrite = new FileStream(sFilename, FileMode.Create,FileAccess.Write);









Dec 8, 2011 at 4:32 PM

I have a couple thoughts:

1.  Why use separate streams for reading and writing?  I use the same stream object when I open and save, and haven't had problems doing it that way

2.  I usually close the stream immediately after initializing the Workbook object.  You do not need to keep the stream open during workbook-object modification (I've actually had issues when leaving it open).  The only time I open the stream is when initializing the workbook and when saving

Dec 8, 2011 at 7:05 PM

Hi Tim,

Maybe the exception is a red herring since the exception is inside the workbook and that may not be the real problem in writing the file.

I will try what you said - use the FileStream and close it after the workbook is created.  Modify the workbook. Then open/use the same FileStream to write it.

Thanks for the information.  I had to deploy a different solution...at 4AM.

I will circle back around on this in the next couple days and post an update. I want to see if I can get it to work because I like the features and quite a few folks are using NPOI and using the discussion/forum.

Thank you,


Dec 9, 2011 at 12:25 AM

Hi Tim

Your solution worked.  So, thank you.

I've switched from that other library back to NPOI and I'll be pushing the change after some testing.