2

在我的 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 () {
                }
            });

我怎样才能完成它?先感谢您。

4

2 回答 2

6

为什么不?ramiramilu 使用window.locationand是正确的iframe。我做了同样的事情,但对于 ASP.NET MVC3。

我建议使用返回的控制器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");
    }

在模型中(如果你愿意,你可以删除静态,并用实例调用它)

public static byte[] GetExcel(XLWorkbook wb)
{
    using (var ms = new MemoryStream())
    {
        wb.SaveAs(ms);
        return ms.ToArray();
    }
}

阿贾克斯:

$.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);
                }
            }
        });

顺便说一句,我删除了所有异常处理程序以简化代码,但我假设你可以自己做。

于 2015-05-14T20:24:53.077 回答
3

您不能使用 AJAX 直接下载文件,但您可以结合 AJAX 下载文件以下载window.location文件。我的意思是,如果您使用 AJAX GET/POST,所有文件内容都将在浏览器的内存中,但不能保存到磁盘(由于 JavaScript 限制)。

相反,您可以使用window.location指向一个 URL,该 URL 反过来将获取文件并提示保存/打开提示。或者,您可以使用隐藏iFrame并设置srciFrame 的属性,其中包含将下载文件的 URL。

于 2015-01-10T09:30:01.217 回答