用asp.net mvc中的ajax jquery在Excel文件中导出数据表

你好我的代码我的控制器行动:

public ActionResult ExportExcel() { DataTable dt = new DataTable(); FILL DataTable try { FileExcel(dt); return Json(new { successCode = "1" }); } catch (Exception ex) { return Json(new { successCode = "0" }); } } public void FileExcel(DataTable dt) { GridView gv = new GridView(); gv.DataSource = dt; gv.DataBind(); HttpContext context = System.Web.HttpContext.Current; context.Response.ClearContent(); context.Response.Buffer = true; context.Response.AddHeader("content-disposition", "attachment; filename=Ricerca.xls"); context.Response.ContentType = "application/ms-excel"; context.Response.Charset = ""; StringWriter sw = new StringWriter(); HtmlTextWriter htw = new HtmlTextWriter(sw); gv.RenderControl(htw); context.Response.Output.Write(sw.ToString()); context.Response.Flush(); htw.Close(); sw.Close(); context.Response.End(); } 

我的Ajax Jquery函数

 function ExportExcel() { $.ajax({ type: "POST", url: '/Home/ExportExcel/', beforeSend: function () { AjaxStart('...Export'); }, success: function (data, textStatus, jqXHR) { AjaxStop(); alert('success') }, error: function (failure) { alert('error'); } }); } 

如果我通过一个简单的链接调用ajax函数ExportExcel()

 <a href="#" onclick="ExportExcel();">Export Excel Ajax</a> 

它不起作用!!!!!!

而如果使用简单的控制器动作

 @Html.ActionLink("Export Excel", "ExportExcel", "Home") 

保存的excel文件出现! 我想用第一种方法(ajax)来pipe理延迟

阿贾克斯不这样工作。 您在成功函数中的数据variables中提供了excel文件的数据,但您将无法将其另存为文件。 尝试将此行添加到成功函数并为您自己查看:

 alert(data); 

你可能能够通过一个0宽度和高度的iframe来实现你想要的。

如果你正在寻找通过JavaScript触发下载,请尝试从这个问题的答案如何在Asp.Net MVC中导出为Excel? 。

 function ExportExcel() { window.open('/Home/ExportExcel/'); } 

我们可以通过cdn获取Tabletools flash swf文件提供保存pdf文件的能力。 我们将使用人口表。 请通过这个网站

http://www.infinetsoft.com/Post/How-to-export-jQuery-datatables-to-MS-excel-in-asp-net-MVC/1192#.VzCATYR97IU