在我的ASP.NET MVC项目中,我使用ClosedXML生成了一个excel文件。
它在非ajax调用中效果很好。这是我的控制器动作方法
// Prepare the response Response.Clear(); Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; Response.AddHeader("content-disposition", "attachment;filename=\"" + reportHeader + ".xlsx\""); // Flush the workbook to the Response.OutputStream using (MemoryStream memoryStream = new MemoryStream()) { MyWorkBook.SaveAs(memoryStream); memoryStream.WriteTo(Response.OutputStream); memoryStream.Close(); } Response.End();
现在,我正在尝试通过ajax请求来执行此操作。但是文件不是从mvc控制器发送的。
$.ajax({ url: url, type: "POST", data: fd, processData: false, contentType: false, beforeSend: function () { }, success: function (response) { }, error: function (request, status, error) { }, complete: function () { } });
我该怎么办呢?先感谢您。
为什么不?ramiramilu关于使用window.location和是正确的iframe。除了ASP.NET MVC3,我做过同样的事情。
window.location
iframe
我建议使用返回的控制器 FileContentResult
FileContentResult
仅供参考,关于FileContentResult MSDN
最后,我是如何做到的(控制器):
[HttpPost] public HttpStatusCodeResult CreateExcel() { XLWorkbook wb = new XLWorkbook(XLEventTracking.Disabled); //create Excel //Generate information for excel file // ... if (wb != null) { Session["ExcelResult"] = wb; return new HttpStatusCodeResult(HttpStatusCode.OK); } return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } [HttpGet] public FileContentResult ExcelResult(string reportHeader) //it's your data passed to controller { byte[] fileBytes = GetExcel((XLWorkbook)Session["ExcelResult"]); return File(fileBytes, MediaTypeNames.Application.Octet, reportHeader + ".xlsx"); }
在模型中(您可以根据需要删除static,并使用实例调用它)
public static byte[] GetExcel(XLWorkbook wb) { using (var ms = new MemoryStream()) { wb.SaveAs(ms); return ms.ToArray(); } }
AJAX:
$.ajax({ url: "@Url.Action("CreateExcel")", async: true, type: "POST", traditional: true, cache: false, statusCode: { 400: function () { alert("Sorry! We cannot process you request"); }, 200: function () { $("#fileHolder") .attr('src', '@Url.Action("ExcelResult")?reportHeader=' + reportHeader); } } });
顺便说一句,我删除了所有异常处理程序以简化代码,但是我想您可以自己做。