MoShe MoShe - 5 months ago 66
C# Question

Exception while import from excel using openXML

I would like to deserialize all the data from the excel file to list.

I am using this code

class ExcelImport
Workbook workBook;
SharedStringTable sharedStrings;
IEnumerable<Sheet> workSheets;
WorksheetPart custSheet;
WorksheetPart orderSheet;
string FilePath;
ExcelStorage provider;
Stiker[] ans;
List<Stiker> StikerList;

public ExcelImport(string fp)
FilePath = fp;


public List<Stiker> dothejob()
using (SpreadsheetDocument document =
SpreadsheetDocument.Open(FilePath, true))
StikerList= new List<Stiker>();
workBook = document.WorkbookPart.Workbook;
workSheets = workBook.Descendants<Sheet>();
sharedStrings = document.WorkbookPart.SharedStringTablePart.SharedStringTable;
StikerList = Stiker.LoadStiker(custSheet.Worksheet, sharedStrings);
return StikerList;

But from some reson I get exception in the line:
sharedStrings =

that "Object reference not set to an instance of an object.".

After the above saggestion found that the

if (sharedStringTablePart == null)
// report a problem

rerurn null

Any idea?


One of the properties in the source line will be "null" and have no value.

You'll want to either use a debugger to figure this out (set a breakpoint on the line and hover the mouse over each property), or break down the line into separate statements. Something like:

var workBookPart = document.WorkbookPart;

if (workBookPart == null)
    // do something to report a problem

var sharedStringTablePart = workBookPart.SharedStringTablePart;
if (sharedStringTablePart == null)
    // report a problem

sharedStrings = sharedStringTablePart.SharedStringTable;

This way your code can determine at run-time if there's an issue: this kind of "defensive" idea is usually a good idea when working with data created by some system other than your own.