Download Excel file via AJAX MVC

后端 未结 14 1771
说谎
说谎 2020-11-22 02:30

I have a large(ish) form in MVC.

I need to be able to generate an excel file containing data from a subset of that form.

The tricky bit is that this shouldn

14条回答
  •  长情又很酷
    2020-11-22 03:19

    First Create the controller action that will create the Excel File

    [HttpPost]
    public JsonResult ExportExcel()
    {
        DataTable dt = DataService.GetData();
        var fileName = "Excel_" + DateTime.Now.ToString("yyyyMMddHHmm") + ".xls";
    
        //save the file to server temp folder
        string fullPath = Path.Combine(Server.MapPath("~/temp"), fileName);
    
        using (var exportData = new MemoryStream())
        {
            //I don't show the detail how to create the Excel, this is not the point of this article,
            //I just use the NPOI for Excel handler
            Utility.WriteDataTableToExcel(dt, ".xls", exportData);
    
            FileStream file = new FileStream(fullPath, FileMode.Create, FileAccess.Write);
            exportData.WriteTo(file);
            file.Close();
        }
    
        var errorMessage = "you can return the errors in here!";
    
        //return the Excel file name
        return Json(new { fileName = fileName, errorMessage = "" });
    }
    

    then create the Download action

    [HttpGet]
    [DeleteFileAttribute] //Action Filter, it will auto delete the file after download, 
                          //I will explain it later
    public ActionResult Download(string file)
    {
        //get the temp folder and file path in server
        string fullPath = Path.Combine(Server.MapPath("~/temp"), file);
    
        //return the file for download, this is an Excel 
        //so I set the file content type to "application/vnd.ms-excel"
        return File(fullPath, "application/vnd.ms-excel", file);
    }
    

    if you want to delete the file after downloaded create this

    public class DeleteFileAttribute : ActionFilterAttribute
    {
        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            filterContext.HttpContext.Response.Flush();
    
            //convert the current filter context to file and get the file path
            string filePath = (filterContext.Result as FilePathResult).FileName;
    
            //delete the file after download
            System.IO.File.Delete(filePath);
        }
    }
    

    and finally ajax call from you MVC Razor view

    //I use blockUI for loading...
    $.blockUI({ message: '

    Please wait a moment...

    ' }); $.ajax({ type: "POST", url: '@Url.Action("ExportExcel","YourController")', //call your controller and action contentType: "application/json; charset=utf-8", dataType: "json", }).done(function (data) { //console.log(data.result); $.unblockUI(); //get the file name for download if (data.fileName != "") { //use window.location.href for redirect to download action for download the file window.location.href = "@Url.RouteUrl(new { Controller = "YourController", Action = "Download"})/?file=" + data.fileName; } });

提交回复
热议问题