I used to export data to excel in asp.net mvc using below code
Response.AppendHeader(\"content-disposition\", \"attachment;filename=ExportedHtml.xls\");
Agreed with David Liang's answer.
Slide modifications if want to export whole DataTable.
string export="export";
DataTable dt = new DataTable();
//Fill datatable
dt = *something*
byte[] fileContents;
using (var package = new ExcelPackage())
{
var worksheet = package.Workbook.Worksheets.Add(export);
worksheet.Cells["A1"].LoadFromDataTable(dt, true);
fileContents = package.GetAsByteArray();
}
if (fileContents == null || fileContents.Length == 0)
{
return NotFound();
}
return File(
fileContents: fileContents,
contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
fileDownloadName: export + ".xlsx"
);