Export Html Table data to Excel in ASP.Net MVC

Export Html Table data to Excel in ASP.Net MVC

To export HTML table data to Excel in ASP.NET MVC, you can use a third-party library such as EPPlus or NPOI.

Here’s an example using EPPlus:

  1. Install the EPPlus library using NuGet Package Manager.
  2. In the controller, retrieve the data that you want to export to Excel and store it in a list or a data table.
  3. Create a new ExcelPackage object and add a new worksheet to it.
  4. Use a for loop to iterate through the data and add each row to the worksheet.
  5. Set the content type to “application/vnd.openxmlformats-officedocument.spreadsheetml.sheet” and the file name to “ExportedData.xlsx”.
  6. Return the ExcelPackage as a FileContentResult.

Here’s an example code to achieve the above steps:

using System.Data;
using OfficeOpenXml;

public FileContentResult ExportToExcel(List<YourModel> modelData)
    DataTable dt = new DataTable("Data");
    dt.Columns.AddRange(new DataColumn[3]
        new DataColumn("ID", typeof(int)),
        new DataColumn("Name", typeof(string)),
        new DataColumn("Address", typeof(string))

    foreach (var item in modelData)
        dt.Rows.Add(item.ID, item.Name, item.Address);

    using (ExcelPackage pck = new ExcelPackage())
        ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Data");
        ws.Cells["A1"].LoadFromDataTable(dt, true);
        return File(pck.GetAsByteArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "ExportedData.xlsx");

Note: This example exports the data to an .xlsx file, but you can also export it to .csv or other formats.

Leave a Comment