Download Excel file via AJAX MVC

后端 未结 14 1789
说谎
说谎 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:11

    I may sound quite naive, and may attract quite a criticism, but here's how I did it,
    (It doesn't involve ajax for export, but it doesn't do a full postback either )

    Thanks for this post and this answer.
    Create a simple controller

    public class HomeController : Controller
    {               
       /* A demo action
        public ActionResult Index()
        {           
            return View(model);
        }
       */
        [HttpPost]
        public FileResult ExportData()
        {
            /* An example filter
            var filter = TempData["filterKeys"] as MyFilter;
            TempData.Keep();            */
            var someList = db.GetDataFromDb(/*filter*/) // filter as an example
    
        /*May be here's the trick, I'm setting my filter in TempData["filterKeys"] 
         in an action,(GetFilteredPartial() illustrated below) when 'searching' for the data,
         so do not really need ajax here..to pass my filters.. */
    
         //Some utility to convert list to Datatable
         var dt = Utility.ConvertToDataTable(someList); 
    
          //  I am using EPPlus nuget package 
          using (ExcelPackage pck = new ExcelPackage())
          {
              ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Sheet1");
              ws.Cells["A1"].LoadFromDataTable(dt, true);
    
                using (var memoryStream = new MemoryStream())
                {                   
                  pck.SaveAs(memoryStream);
                  return File(memoryStream.ToArray(),
                  "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                  "ExportFileName.xlsx");                    
                }                
            }   
        }
    
        //This is just a supporting example to illustrate setting up filters ..        
       /* [HttpPost]
        public PartialViewResult GetFilteredPartial(MyFilter filter)
        {            
            TempData["filterKeys"] = filter;
            var filteredData = db.GetConcernedData(filter);
            var model = new MainViewModel();
            model.PartialViewModel = filteredData;
    
            return PartialView("_SomePartialView", model);
        } */     
    } 
    

    And here are the Views..

    /*Commenting out the View code, in order to focus on the imp. code     
     @model Models.MainViewModel
     @{Layout...}     
    
          Some code for, say, a partial View  
          
    @Html.Partial("_SomePartialView", Model.PartialViewModel)
    */ //The actual part.. Just **posting** this bit of data from the complete View... //Here, you are not posting the full Form..or the complete View @using (Html.BeginForm("ExportData", "Home", FormMethod.Post)) { } //... //
    /*And you may require to pass search/filter values.. as said in the accepted answer.. That can be done while 'searching' the data.. and not while we need an export..for instance:- */

    The whole point of the trick seems that, we are posting a form (a part of the Razor View ) upon which we are calling an Action method, which returns: a FileResult, and this FileResult returns the Excel File..
    And for posting the filter values, as said, ( and if you require to), I am making a post request to another action, as has been attempted to describe..

提交回复
热议问题