下载从ASP.NET MVC的jQuery Ajax请求的Excel文件 [英] Download an excel file in JQuery-AJAX request from ASP.NET MVC

查看:2951
本文介绍了下载从ASP.NET MVC的jQuery Ajax请求的Excel文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的ASP.NET MVC项目,我产生用excel文件 ClosedXML

In my ASP.NET MVC project, I generated a excel file using ClosedXML.

它运作良好,在非Ajax调用。这是我的控制器的操作方法

It works well in non-ajax call. Here is my controller action method

 // 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控制器发送。

Now I am trying to do it via an ajax request. But the file is not sent from 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 () {
                }
            });

我怎样才能做到呢? 谢谢你在前进。

How can i accomplish it? Thank you in advance.

推荐答案

为什么不呢? ramiramilu是对关于使用 window.location的 IFRAME 。 我也做了同样的事情,但对于ASP.NET MVC3。

Why not? ramiramilu was right about using window.location and iframe. I did the same thing but for ASP.NET MVC3.

我会建议使用控制器,它返回 FileContentResult

I would suggest to use controller which returns FileContentResult

FYI约 FileContentResult MSDN

最后我做到了(控制器):

And finally how I did it (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");
    }

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

In model (you can remove static if you wish, and call it with instance)

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

AJAX:

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

顺便说一句,我删除了所有的异常处理程序,简化了code,但我相信你可以自己做。

BTW, I removed all exception handlers to simplify the code, but I assume You can do it yourself.

这篇关于下载从ASP.NET MVC的jQuery Ajax请求的Excel文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆