如何使用Jquery Ajax MVC下载excel文件和PDF文件

时间:2014-11-03 11:58:50

标签: jquery ajax asp.net-mvc-4 download

我正在使用MVC应用程序。我想使用Jquery AJAX下载excel文件和PDF文件。

在查看页面

 <a href="javascript:void(0)" class="excelbtn" data-is-pdf="false" >Export To Excel</a>
 <a href="javascript:void(0)" class="pdfbtn" data-is-pdf="true">Export To PDF</a>

Jquery ajax

$.ajax({
        type: 'GET',
        url: '/Report/ExportReports',
        contentType:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        data: {
            Parameter1: Parameter1,
            Parameter2: Parameter2,
        },
        cache: false,
        success: function (isSuccess) {
            if (isSuccess.Success) {
                }
            } else {
                alert('Something went wrong. Please try again after sometime...');
            }
        },
        error: function (data, status, e) {
        }
    });

在控制器

public ActionResult ExportReports(string Parameter1, string Parameter2)
    {
       if (Parameter1 = "PDF")
        {
            DataTable exportData = grid.GetExportData(dataSource);
            MemoryStream pdfStream = gridData.ExportToPDF(exportData, repType);

            Response.ClearContent();
            Response.ClearHeaders();
            Response.ContentType = "application/pdf";
            Response.AppendHeader("Content-Disposition", "attachment; filename=" + executeRepType + ".pdf");
            Response.BinaryWrite(pdfStream.ToArray());
            Response.End();
        }
        else
        {
            DataTable exportData = grid.GetExportData(dataSource);
            MemoryStream excelStream = gridData.ExportToExcel(exportData, executeRepType);
            //Write it back to the client
            Response.ClearContent();
            Response.ClearHeaders();
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            Response.AddHeader("content-disposition", "attachment;  filename=" + executeRepType + ".xlsx");
            Response.BinaryWrite(excelStream.ToArray());//.GetAsByteArray());
            Response.End();
        }
        return View();
    }

因此,在控制器中我们获取所有数据但我们无法返回视图页面。

2 个答案:

答案 0 :(得分:3)

您可以尝试此解决方案。 在视图页面

@Html.ActionLink("Export To Excel", "ExportReports", new { isPdfExport = false,Parameter1="_Parameter1" ,Parameter2="_Parameter2"}, new { @class="excelbtn" })

@Html.ActionLink("Export To PDF", "ExportReports", new { isPdfExport = true,Parameter1="_Parameter1" ,Parameter2="_Parameter2"}, new { @class="pdfbtn" })

如果你想动态更改parameter1和parameter2的值,你可以使用javascript,如下所述

在Javascript中: -

$('.excelbtn').attr('href', function () {
        return this.href.replace('_Parameter1', Value1).replace('_Parameter2',Value2);
          });
$('.pdfbtn').attr('href', function () {
        return this.href.replace('_Parameter1', Value1).replace('_Parameter2',Value2);
          });

在控制器中: -

public ActionResult ExportReports(bool isPdfExport,string Parameter1, string Parameter2)
{
   if (Parameter1 = "PDF")
    {
        DataTable exportData = grid.GetExportData(dataSource);
        MemoryStream pdfStream = gridData.ExportToPDF(exportData, repType);

        Response.ClearContent();
        Response.ClearHeaders();
        Response.ContentType = "application/pdf";
        Response.AppendHeader("Content-Disposition", "attachment; filename=" + executeRepType + ".pdf");
        Response.BinaryWrite(pdfStream.ToArray());
        Response.End();
    }
    else
    {
        DataTable exportData = grid.GetExportData(dataSource);
        MemoryStream excelStream = gridData.ExportToExcel(exportData, executeRepType);
        //Write it back to the client
        Response.ClearContent();
        Response.ClearHeaders();
        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        Response.AddHeader("content-disposition", "attachment;  filename=" + executeRepType + ".xlsx");
        Response.BinaryWrite(excelStream.ToArray());//.GetAsByteArray());
        Response.End();
    }
    return View();
}

答案 1 :(得分:0)

我建议你在开箱即用的工具的帮助下更简单地做一些事情。 System.Web.MVC.Controller.File为您提供了一种方法,可以使用字节数组或流或文件路径完成您所需的操作。因此,而不是这部分(和pdf相同)

Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;  filename=" + executeRepType + ".xlsx");
Response.BinaryWrite(excelStream.ToArray());//.GetAsByteArray());
Response.End();

我会用这样的东西

File(excelStream.ToArray(), System.Net.Mime.MediaTypeNames.Application.Octet, executeRepType + ".xlsx");

异步请求中没有实际需要。所以你可以使用直接链接。