Tuesday, February 7, 2023

EPPlus - null reference exception on accessing ExcelPackage object in C#

 Recently I was working on an issue for which I found a resolution, Wanted to share it here.

Issue

Using EPPlus package to manipulate an Excel file is throwing an error saying that the ExcelPackage object is null. While debugging when I hit the object it shows null. If I remove my cursor an hove back on it the object is loaded. This is happening with Excel files generated by code.

Resolution:  

The exception is caught and in the catch block, after a pause of 2 seconds, the ExcelPackage is called again which resolves successfully. This is just a work around for EPPlus version 4.5. I have seen that the issue was resolved in the later versions which are paid. Find the code snippet below.

try{

        ExcelPackage package = new ExcelPackage();

        var xlSheet = package.Workbook.Worksheets[1];

   }

catch(Exception e)

  {

        Thread.Sleep(2000);

        var xlSheet = package.Workbook.Worksheets[1];

 }