jquery - 从 ASP.NET MVC 的 JQuery-AJAX 请求中下载 excel 文件

标签 jquery ajax asp.net-mvc download closedxml

在我的 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.locationiframe 的说法是正确的。 我做了同样的事情,但对于 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/

相关文章:

c# - WebMatrix.WebData.WebSecurity - 如何仅通过 PasswordResetToken 获取用户名

asp.net-mvc - 缺少 'Ajax' 命名空间中不存在 'System.Web.Mvc'

javascript - 基于其他自动完成输入的 jQuery 自动完成选项

javascript - codeigniter 中的自动完成功能不显示任何内容

jquery - 如何获取 bootstrap-fileinput 中的响应数据?

html - bing map 控件不尊重 div

javascript - 基本的 jquery 延迟使用与 ajax

JQuery .html 与 .attr ('innerHTML' )

javascript - jQuery 文件上传库 : how to upload with a click for a SINGLE file

javascript - 如何提交未选中的复选框