OpenXML SDK- Worksheet抛出空引用异常

时间:2013-12-02 12:12:49

标签: c# excel openxml-sdk

我使用下面的代码来从excel文件中检索数据。我注意到WorksheetPart的Worksheet对象抛出空引用异常。谁能告诉我为什么抛出这个异常?我还能做些什么来避免这个错误?

SpreadsheetDocument doc = SpreadsheetDocument.Open("1.xlsx", true);
Sheet sheet = (Sheet)doc.WorkbookPart.Workbook.Sheets.FirstOrDefault();
WorksheetPart worksheetPart = (WorksheetPart)doc.WorkbookPart
                                                .GetPartById(sheet.Id);
Worksheet worksheet = worksheetPart.Worksheet; // throws null reference exception

1 个答案:

答案 0 :(得分:0)

您很可能找不到WorksheetPart,因此当您尝试访问Worksheet属性时,它会抛出空引用异常。尝试以这种方式获取WorksheetPart,其中工作表名称是工作表的名称:

string relId = workbookPart.Workbook.Descendants<Sheet>()
                                 .First(s => sheetName.Equals(s.Name))
                                 .Id;

WorksheetPart workSheetPart = (WorksheetPart)workbookPart.GetPartById(relId);