0

I'm trying to select just the rows from an Excel spreadsheet that have data in the first column.

Here's the code I'm using:

        IEnumerable<Row> dataRows =
          from row in worksheet.Descendants<Row>()
          where (row.RowIndex > 2 
            && row.Descendants<Cell>().First().CellValue != null)
          select row;

When I run this code, the debugger tells me "Error in implicit conversion. Cannot convert null object."

I can't figure out what the null object is. I assume that each row has a non-null first cell (though, of course, the CellValue of the cell in question may be null).

Can anyone tell what I am doing wrong here?

Thanks in advance for your help.

amurra
  • 15,221
  • 4
  • 70
  • 87
Steve
  • 543
  • 1
  • 6
  • 14
  • My problem actually appears to be with the RowIndex property. For some reason, it's null on some of the rows in my spreadsheet. – Steve Apr 30 '12 at 22:08

1 Answers1

0

If a row or cell is empty, it can be null. The null object can be coming from a row that doesn't have a value in the first cell (and was never initialized).

So when you run row.Descendants<Cell>().First().CellValue, the null object is coming from .First(), that cell has not yet been initialized.

Try the following:

IEnumerable<Row> dataRows =
    from row in templateWorksheetPart.Worksheet.Descendants<Row>()
    where (row.RowIndex > 2 
        && row.Descendants<Cell>().First() != null                        
        && row.Descendants<Cell>().First().CellValue != null)
    select row;
Joe Masilotti
  • 16,815
  • 6
  • 77
  • 87