在我的 ASP.NET MVC 项目中,我使用 ClosedXML 生成了一个 excel 文件。 .
它在非ajax调用中运行良好。这是我的 Controller 操作方法
// 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 Controller 发送的。
$.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。
我建议使用返回FileContentResult
的 Controller
仅供引用FileContentResult
MSDN
最后我是如何做到的( Controller ):
[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");
}
在模型中(如果愿意,您可以删除静态,并使用实例调用它)
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);
}
}
});
顺便说一句,我删除了所有异常处理程序以简化代码,但我假设您可以自己完成。
关于jquery - 从 ASP.NET MVC 的 JQuery-AJAX 请求中下载 excel 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27874360/