c# - EPPlus export model to Excel: System.NullReferenceException -


i have mvc view correctly displays model. have been asked put export excel function on page, heard epplus , gave try. this site thought had job.

after making changes fit needs, developed this. when tested functionality in view, worked. clicked html actionlink , excel file saved correctly.

public void exporttoexcel(ienumerable<fourcourseaudit> audit) {   string pathuser = environment.getfolderpath(environment.specialfolder.userprofile);   string pathdownload = path.combine(pathuser, "documents");    fileinfo newfile = new fileinfo(pathdownload + "\\myexport.xslx");    using (var excelfile = new excelpackage(newfile))   {       var worksheet = excelfile.workbook.worksheets.firstordefault(x=>x.name=="sheet1");       if (worksheet == null)        {           worksheet.workbook.worksheets.add("sheet1");       }        worksheet.cells["a1"].loadfromcollection(collection:audit, printheaders:true);       excelfile.save();   } } 

however, when published website , tested normal user, got dreaded "null exception" error: system.nullreferenceexception: object reference not set instance of object.

the possible culprits are:

  • null worksheet
  • null newfile
  • null audit

this puzzling because works when run in debug mode vs, null exception error appears when it's running off production server.

is there obvious i'm doing wrong code example?

you can't (well shouldn't) try save directly user's filesytem web application.

i suspect null reference somewhere in environment.specialfolders... object.

it woud better return file byte array response in controller action. way user choice save file in thier own filesystem. ought trick:

public actionresult exporttoexcel(ienumerable<fourcourseaudit> audit) {     byte[] response;     using (var excelfile = new excelpackage())     {         var worksheet = excelfile.workbook.worksheets.add("sheet1");         worksheet.cells["a1"].loadfromcollection(collection:audit,printheaders:true);         response = excelfile.getasbytearray();     }     return file(response, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "export.xlsx"); } 

Comments

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -