Exporting to Excel

Libraries

Excel reports can be created using one of the following libraries:

NPOI

Installation

Install the latest version of NPOI, according to the official nuget package .

Generation of Excel

Refer to this guide on how to use NPOI to generate an excel file.

Rather than writing the data into a file, we can also write it into a stream object.

using (MemoryStream dataStream = new MemoryStream())  
{  
    IWorkbook workbook = new XSSFWorkbook();  
    ISheet sheet = workbook.CreateSheet("Sheet 1");  
  
    // [redacted code that manipulates contents of the excel sheet]
    
    workbook.Write(dataStream, false);  
  
    return dataStream;  
};

In the excel download endpoint of your project, we can use the stream object to return a File for download.

return File(excelStream.ToArray(), "application/vnd.ms-excel", $"{filename}.xlsx");

For more examples, refer to the official NPOI documentation