Download Excel file via AJAX MVC

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

    using ClosedXML.Excel;

       public ActionResult Downloadexcel()
        {   
            var Emplist = JsonConvert.SerializeObject(dbcontext.Employees.ToList());
            DataTable dt11 = (DataTable)JsonConvert.DeserializeObject(Emplist, (typeof(DataTable)));
            dt11.TableName = "Emptbl";
            FileContentResult robj;
            using (XLWorkbook wb = new XLWorkbook())
            {
                wb.Worksheets.Add(dt11);
                using (MemoryStream stream = new MemoryStream())
                {
                    wb.SaveAs(stream);
                    var bytesdata = File(stream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "myFileName.xlsx");
                    robj = bytesdata;
                }
            }
    
    
            return Json(robj, JsonRequestBehavior.AllowGet);
        }
    
    0 讨论(0)
  • 2020-11-22 03:24

    On Submit form

    public ActionResult ExportXls()
    {   
     var filePath="";
      CommonHelper.WriteXls(filePath, "Text.xls");
    }
    
     public static void WriteXls(string filePath, string targetFileName)
        {
            if (!String.IsNullOrEmpty(filePath))
            {
                HttpResponse response = HttpContext.Current.Response;
                response.Clear();
                response.Charset = "utf-8";
                response.ContentType = "text/xls";
                response.AddHeader("content-disposition", string.Format("attachment; filename={0}", targetFileName));
                response.BinaryWrite(File.ReadAllBytes(filePath));
                response.End();
            }
        }
    
    0 讨论(0)
提交回复
热议问题