How to Export data to Excel file with ASP.NET MVC
By FoxLearn 2/18/2024 2:11:53 AM 60
The export to Excel functionality is implemented using the ClosedXML.Excel NuGet Package or download it directly from https://github.com/ClosedXML/ClosedXML, as shown in this example.
We will install ClosedXML.Excel library from the Nuget Packages Manager
What is the NuGet package manager?
It's a tool that allows you to let developers to create, share, and consume useful . NET libraries. NuGet client tools provide the ability to produce and consume these libraries as "packages"
The ClosedXML library makes it easier for developers to create Excel (.xlsx, .xlsm, etc) files. It provides a nice object orientation for manipulating files without having to handle the complexity of XML documents. It can be used by any .NET language such as C# and VB.NET.
public FileResult Export() { if (TempData["Invoices"] != null) { DataTable dt = new DataTable("Invoices"); dt.Columns.AddRange(new DataColumn[7] { new DataColumn("RowNumber"), new DataColumn("InvoiceNumber"), new DataColumn("BuyerName"), new DataColumn("BuyerAddress"), new DataColumn("BuyerEmail"), new DataColumn("Total"), new DataColumn("InvoiceDate") }); foreach (var item in TempData["Invoices"] as List<InvoiceInfo> ) dt.Rows.Add(item.RowNumber, item.InvoiceNumber, item.BuyerName, item.BuyerAddress, item.BuyerEmail, item.Total, item.InvoiceDate); TempData.Keep("Invoices"); using (XLWorkbook wb = new XLWorkbook()) { wb.Worksheets.Add(dt); using (MemoryStream stream = new MemoryStream()) { wb.SaveAs(stream); return File(stream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Invoices.xlsx"); } } } throw new HttpException(404, "File not found !"); }
You can get data from TempData or get directly from your database, in this tutorial i'm using TempData
ClosedXML allows you to create Excel 2007 version (.xlsx, .xlsm, etc) files without the Excel application. The typical example is creating Excel reports on a web server.
- Could not load file or assembly 'netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies
- How to fix "InvalidOperationException: No service for type 'Microsoft.AspNetCore.Identity.UserManager'"
- How to fix 'IMvcBuilder' does not contain a definition for 'AddNewtonsoftJson'
- ASP.NET Core: How to Create RDLC Report in ASP.NET Core
- ASP.NET MVC: Free Responsive Templates
- How to fix Assets file 'project.assets.json' not found
- How to fix 'DbContextOptionsBuilder' does not contain a definition for 'UseSqlServer'
- How to set cookie ValidationInterval in ASP.NET Core