Standalone Method to Create Workbook from IFormFile Resulting in Null Worksheets object

Hello,

I am using XlsIO version 19.1.0.54 and am accepting a user's upload of an Excel book from a browser to a .Net Core 3.x backend. I have the following code which works when it is in-line in the method (the variable firstSheet has data):


// Instantiate the Excel application object
using var excelEngine = new ExcelEngine();
var application = excelEngine.Excel;

// Assigns default application version
application.DefaultVersion = ExcelVersion.Excel2016;

using var ms = new MemoryStream();
await file.CopyToAsync(ms, cancellationToken);
ms.Position = 0;

var workbook = application.Workbooks.Open(ms);
var firstSheet = workbook.Worksheets[0];


Howeverwhen I extract that to its own method like the following, the last line where I access the Worksheetsproperty just returns null:


private async Task ExtractExcelFromFile(IFormFile file, CancellationToken cancellationToken)
{
// Instantiate the Excel application object
using var excelEngine = new ExcelEngine();
var application = excelEngine.Excel;

// Assigns default application version
application.DefaultVersion = ExcelVersion.Excel2016;

using var ms = new MemoryStream();
await file.CopyToAsync(ms, cancellationToken);
ms.Position = 0;

var workbook = application.Workbooks.Open(ms);
return workbook;
}

Thank you.


1 Reply

KK Konduru Keerthi Konduru Ravichandra Raju Syncfusion Team January 31, 2023 01:59 PM UTC

Hi Doug,


As you are initializing the ExcelEngine inside the method, it gets disposed after the method execution ends. Hence your workbook.Worksheets property is returned as null when access outside the method.


We suggest you to initialize the ExcelEngine outside the method to overcome the reported issue. Please find the example code below.


Existing Scenario

Proposed Scenario

static void Main(string[] args)

{

    IWorkbook book = ExtractExcelFromFile();

}

private static IWorkbook ExtractExcelFromFile()

{

    // Instantiate the Excel application object

    using var excelEngine = new ExcelEngine();

    var application = excelEngine.Excel;

 

    // Assigns default application version

    application.DefaultVersion = ExcelVersion.Excel2016;

 

    IWorkbook workbook = application.Workbooks.Create(1);

    return workbook;

}

ExcelEngine excelEngine = new ExcelEngine();

static void Main(string[] args)

{

    Program obj = new Program();

    IWorkbook book = obj.ExtractExcelFromFile();

}

private IWorkbook ExtractExcelFromFile()

{

    var application = excelEngine.Excel;

 

    // Assigns default application version

    application.DefaultVersion = ExcelVersion.Excel2016;

 

    IWorkbook workbook = application.Workbooks.Create(1);

    return workbook;

}


Regards,

Keerthi.


Loader.
Up arrow icon