Export to Excel in ASP.Net Core 2.0

前端 未结 3 679
既然无缘
既然无缘 2021-02-07 23:13

I used to export data to excel in asp.net mvc using below code

    Response.AppendHeader(\"content-disposition\", \"attachment;filename=ExportedHtml.xls\");
            


        
3条回答
  •  误落风尘
    2021-02-07 23:53

    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"
                );
    

提交回复
热议问题