无法在空引用上执行运行时绑定 – 清空Excel单元格

我似乎无法想出一种方法来纠正标题中提到的错误,并正在寻找应该做什么的一些想法。

我正在尝试将excel电子表格的行读取到对象中。

第一次循环我没有问题,因为行1,列1和行1列2中有数据。

但是,当它到达第2行,第1列和第2行第2列时,由于上述错误而失败,因为电子表格中的这些单元格是“空的”

我只是不能在那里我可以把一些“如果空”检查。

任何人都可以build议如何做到这一点?

这是我的代码…

private static void IterateRows(Excel.Worksheet worksheet) { //Get the used Range Excel.Range usedRange = worksheet.UsedRange; // create an object to store the spreadsheet data List<SPREADSHEETModel.spreadsheetRow> spreadsheetrows = new List<SPREADSHEETModel.spreadsheetRow>(); //Iterate the rows in the used range foreach (Excel.Range row in usedRange.Rows) { for (int i = 0; i < row.Columns.Count; i++) { spreadsheetrows.Add(new SPREADSHEETModel.spreadsheetRow() { col1 = row.Cells[i + 1, 1].Value2.ToString(), col2 = row.Cells[i + 1, 2].Value2.ToString() }); } } } 

不要使用.ToString() ,当值为null时,会引起null reference exception 。 使用Convert.ToString() ,它将返回空值的空string。

 col1 = Convert.ToString(row.Cells[i + 1, 1].Value2); col2 = Convert.ToString(row.Cells[i + 1, 2].Value2); 

在调用ToString之前,您需要它们。 也许你甚至可以在添加之前移动,因为我认为添加空行是没有用的,但是在你的场景中这可能是正确的:

 if (row.Cells[i + 1, 1].Value2 != null && row.Cells[i + 1, 2].Value2 != null) { spreadsheetrows.Add(new SPREADSHEETModel.spreadsheetRow() { col1 = row.Cells[i + 1, 1].Value2.ToString(), col2 = row.Cells[i + 1, 2].Value2.ToString() }); } 

否则,这可能是你所需要的:

 col1 = row.Cells[i + 1, 1].Value2 != null ? row.Cells[i + 1, 1].Value2.ToString() : null, 

这个exception的原因是Value2是一个dynamic ,所以返回值是在运行时确定的。 如果Value2null ,则无法确定要调用的ToString方法。

你可以检查循环内部:

  //Iterate the rows in the used range foreach (Excel.Range row in usedRange.Rows) { for (int i = 0; i < row.Columns.Count; i++) { spreadsheetrows.Add(new SPREADSHEETModel.spreadsheetRow() { if (row.Cells[i + 1, 1].Value2 != null) { col1 = row.Cells[i + 1, 1].Value2.ToString(); } if (row.Cells[i + 1, 2].Value2 != null) { col2 = row.Cells[i + 1, 2].Value2.ToString(); } if (row.Cells[i + 1, 3].Value2 != null) { col3 = row.Cells[i + 1, 3].Value2.ToString(); } }); } }