Export to Excel in ASP.Net Core 2.0

前端 未结 3 681
既然无缘
既然无缘 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-08 00:16

    There are many ways to achieve that.

    Option 1: save to wwwroot

    You can generate the Excel and save it to the wwwroot folder. And then you can serve it as static content on the page.

    For example you have a folder called 'temp' inside the wwwroot folder to contain all the newly generated excels.

    Download
    

    There are limitations on this approach. 1 of them is the new download attribute. It only works on modern browsers.

    Option 2: byte array

    Another way is to generate the Excel, convert it into byte array and send it back to the controller. For that I use a library called "EPPlus" (v: 4.5.1) which supports .Net Core 2.0.

    The following is just some sample codes I put together to give you an idea. It's not production ready.

    using OfficeOpenXml;
    using OfficeOpenXml.Style;
    
    namespace DL.SO.Web.UI.Controllers
    {
        public class ExcelController : Controller
        {
            public IActionResult Download()
            {
                byte[] fileContents;
    
                using (var package = new ExcelPackage())
                {
                    var worksheet = package.Workbook.Worksheets.Add("Sheet1");
    
                    // Put whatever you want here in the sheet
                    // For example, for cell on row1 col1
                    worksheet.Cells[1, 1].Value = "Long text";
    
                    worksheet.Cells[1, 1].Style.Font.Size = 12;
                    worksheet.Cells[1, 1].Style.Font.Bold = true;
    
                    worksheet.Cells[1, 1].Style.Border.Top.Style = ExcelBorderStyle.Hair;
    
                    // So many things you can try but you got the idea.
    
                    // Finally when you're done, export it to byte array.
                    fileContents = package.GetAsByteArray();
                }
    
                if (fileContents == null || fileContents.Length == 0)
                {
                    return NotFound();
                }
    
                return File(
                    fileContents: fileContents,
                    contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                    fileDownloadName: "test.xlsx"
                );
            }
        }
    }
    

提交回复
热议问题