NullReferenceException in creating Excel worksheet NullReferenceException in creating Excel worksheet asp.net asp.net

NullReferenceException in creating Excel worksheet


change line 562 of ExcelWorksheet.cs from:

XmlNode pageSetup = _worksheetXml.SelectSingleNode("//d:pageSetup", NameSpaceManager);

to:

XmlNode pageSetup = WorksheetXml.SelectSingleNode("//d:pageSetup", NameSpaceManager);

If the worksheet has not been accessed, calling the public accessor WorksheetXml instead of the private class variable initiallizes it correctly.


Catching the null reference exception being thrown by the xlPackage.Save() method, and dumping the stack trace, the problem seems to be getting caused by ExcelWorksheet.cs:line 561 which corresponds to this line in the source:

XmlNode pageSetup = _worksheetXml.SelectSingleNode("//d:pageSetup", NameSpaceManager);

Interestingly enough, if you catch the exception the xlsx files seems to save ok anyway (at least for me it does, there might be some unexpected behaviour, but I couldn't produce any).

I'd try handle the exception and seeing if you file is actually saving. It might be worth raising an issue on the ExcelPackage site if this is a library you're going to be using a lot (I don't)

EDIT:

It seems that the ExcelPackage library is quite old and not maintained. I'd have a look at the EPPlus library, which is based on ExcelPackage. You'll need to tweak a bit of your code but nothing major. Saving works without problem.

http://epplus.codeplex.com/


I'd recommend looking into the Microsoft.Office.Interop.Excel reference. I wish there was more intellisense, but it's pretty easy to figure out.

I've set my using as:

using Excel = Microsoft.Office.Interop.Excel;

I'm guessing you'll want the application to be invisible:

Excel.Application application = new Excel.Application();application.Visible = false;

I've not used HttpContext, but if it's a path, then I'd advise using the Path class:

string filename = "DBE_BAKIM_FORMU.xlsx";Excel.Workbook book = application.Workbooks.Open(Path.Combine(HttpContext.Current.Server.MapPath("~/"), filename));

The code should be similar, here's how to grab a sheet and fill cells:

Excel.Worksheet sheet = book.Worksheets[1];sheet.Cells[6, 3].Value2 = "Something";

Saving and closing:

book.Save();book.Close();

The Microsoft.Office.Interop.Excel reference is included in Visual Studio 2012, and 2010 if you're still using that version. Excel is required on the machine with the executable.

Best of luck!