Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use NPOI to read Excel spreadsheet that contains empty cells?

Tags:

c#

excel

npoi

When I read Excel worksheet using NPOI, empty cells are skipped. For example, it the row contains A, B, , C and I read it using

IRow row = sheet.GetRow(rowNb)

then row.Cells[1].ToString() will output B (as expected) but row.Cells[2].ToString() will output C instead of an empty string. Is there a way to keep empty cells? Thanks.

like image 591
Yulia V Avatar asked Jul 04 '13 17:07

Yulia V


2 Answers

Try the GetCell method with the MissingCellPolicy:

ICell cell = row.GetCell(2, MissingCellPolicy.RETURN_NULL_AND_BLANK);
like image 67
Richard Deeming Avatar answered Nov 08 '22 23:11

Richard Deeming


In completion to the accepted answer, the policy can be set on the workbook level as well

workbook.MissingCellPolicy = MissingCellPolicy.RETURN_NULL_AND_BLANK;

This way the policy is applied implicitly when you call GetCell, no need to pass it every time as a parameter

ICell cell = row.GetCell(2);

Note that (at least in the version I'm using) if you do row.Cells[index], it ignores the policy so it only works if you call row.GetCell(index)

like image 29
SzilardD Avatar answered Nov 08 '22 23:11

SzilardD