Excel结果没有给我任何东西,但运行正常

我使用这个AJAX在控制器上调用我的Excel Export操作:

$("#ExportToExcel").click(function () { // ajax call to do the export var urlString = ""; var Jsondata = { id: GetGUIDValue(), viewName: "", fileName: 'Cashflows.xls' } $.ajax({ type: "POST", url: urlString, data: Jsondata, success: function (data) { } }); }); 

这是动作的样子:

 public ActionResult ExportToExcel(Guid? id, string viewName, string fileName) { IndicationBase indication = CachedTransactionManager.GetCachedTransactions(id.Value); return new ExcelResult ( ControllerContext, viewName, fileName, indication.Model ); } 

Firebug运行良好,没有错误,运行时代码也没有错误,但屏幕上没有弹出任何内容。 我希望看到一个保存对话框来保存excel文件。

我究竟做错了什么?

编辑:这是我的自定义操作,

 public class ExcelResult : ActionResult { string _fileName; string _viewPath; Model _model; ControllerContext _context; public ExcelResult(ControllerContext context, string viewPath, string fileName, Model model) { this._context = context; this._fileName = fileName; this._viewPath = viewPath; this._model = model; } protected string RenderViewToString() { using (var writer = new StringWriter()) { var view = new WebFormView(_viewPath); var vdd = new ViewDataDictionary(_model); var viewCxt = new ViewContext(_context, view, vdd, new TempDataDictionary(), writer); viewCxt.View.Render(viewCxt, writer); return writer.ToString(); } } void WriteFile(string content) { HttpContext context = HttpContext.Current; context.Response.Clear(); context.Response.AddHeader("content-disposition", "attachment;filename=" + _fileName); context.Response.Charset = ""; context.Response.Cache.SetCacheability(HttpCacheability.NoCache); context.Response.ContentType = "application/ms-excel"; context.Response.Write(content); context.Response.End(); } public override void ExecuteResult(ControllerContext context) { string content = this.RenderViewToString(); this.WriteFile(content); } } 

您无法在ajax查询上调用文件下载,因为浏览器不会触发文件下载弹出窗口。

不要对控制器方法执行ajax调用,只需使用a

 windows.open("yoururl/ExportToExcel?id=yourid&etc...", null, null, null); 

不要忘记添加你的论点。

希望这可以帮助

我使用FileContentResult实现了对Excel的导出。 它会为您处理设置响应标头。 没有必要重新发明轮子。 😉

不知道它是否有用,但我可以推荐EPPlus库来加载和处理Excel文件。

您可以尝试将POST转换为GET并直接渲染标记吗? 我认为IE在AJAX请求期间没有采用内容处理方式。