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

时间:2022-01-13 09:45:17

I am using MVC Application. I want to download excel file and PDF file using Jquery AJAX.

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

In View page

在视图页面中

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

In Controller

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

So in controller we are getting the all data but we are not able return into view page.

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

2 个解决方案

#1


3  

You can try this Solution. In View Page

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

@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" })

if you want to Change the value of parameter1 and parameter2 dynamically than you can use javascript as describe below

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

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

In Controller:-

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

#2


0  

I would suggest you to make things a bit more simply with help of tools which are coming out of the box. The System.Web.MVC.Controller.File provides you a method which will do exactly what you need using byte array or stream or file path. So instead of this part (and same for pdf)

我建议你在开箱即用的工具的帮助下更简单地做一些事情。 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();

I would use something like this

我会用这样的东西

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

And there is no actual need in async request. So you can just use direct link.

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

#1


3  

You can try this Solution. In View Page

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

@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" })

if you want to Change the value of parameter1 and parameter2 dynamically than you can use javascript as describe below

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

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

In Controller:-

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

#2


0  

I would suggest you to make things a bit more simply with help of tools which are coming out of the box. The System.Web.MVC.Controller.File provides you a method which will do exactly what you need using byte array or stream or file path. So instead of this part (and same for pdf)

我建议你在开箱即用的工具的帮助下更简单地做一些事情。 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();

I would use something like this

我会用这样的东西

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

And there is no actual need in async request. So you can just use direct link.

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