使用OpenXML访问Excel行中的单元格值 – 未将对象引用设置为对象的实例

我有一个需要从Excel电子表格读取值并将值保存到数据库。 问题,我似乎在这个时候正在访问我的行对象中的列中的单个值

http://msdn.microsoft.com/en-us/library/office/documentformat.openxml.spreadsheet.cellvalue.aspx

var cellValues = from cell in row.Descendants<Cell>() select (cell.DataType != null && cell.DataType.HasValue && cell.DataType == CellValues.SharedString && int.Parse(cell.CellValue.InnerText) < sharedString.ChildElements.Count ? sharedString.ChildElements[int.Parse(cell.CellValue.InnerText)].InnerText : cell.CellValue.InnerText); 

不幸的是,上面的代码似乎没有做这项工作,因为它在运行时会引发exception,所以如何使用OpenXML访问包含在Excel Row对象中的值的最佳想法。

+ $ exception {“对象引用未设置为对象的实例”} System.Exception {System.NullReferenceException}

结果StackTrace

  at MOC.Import.Products.<ProcessRows>b__0(Cell cell) in c:\Development\CFrontEnd\MOC.Import\Products.cs:line 37 at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext() at System.Linq.Enumerable.Count[TSource](IEnumerable`1 source) at MOC.Import.Products.ProcessRows(IEnumerable`1 dataRows, SharedStringTable sharedString) in c:\Development\CFrontEnd\MOC.Import\Products.cs:line 45 

您引用的对象之一是null。 find导致问题的特定对象的最简单方法是从LINQexpression式中取出过滤和格式化代码,并遍历单元格:

 var cellValues = from cell in row.Descendants<Cell>() select cell; foreach (var cell in cellValues) { if(cell.DataType != null && cell.DataType.HasValue && cell.DataType == CellValues.SharedString && int.Parse(cell.CellValue.InnerText) < sharedString.ChildElements.Count) { DoSomething(sharedString.ChildElements[int.Parse(cell.CellValue.InnerText)].InnerText); } else { DoSomething(cell.CellValue.InnerText); } } 

使用这个结构,将很容易在debugging器中检测到问题。 您还可以更多地展开此代码,并添加更多针对空值的警戒,以使您的代码更健壮。 简而言之,您的问题是您对正在阅读的文档的结构做出了无效的假设。 作为一般规则,假设是不好的,特别是当它们是对你没有完全控制权的投入的假设时。