0

I'm trying to generate and download Excel file using ASP.NET static WebMethod, which is called via Ajax from jQuery.

[WebMethod]
public static void ExportToExcel(List<ResultGroupItem> searchResult)
{
    HttpResponse response = HttpContext.Current.Response;

    ExcelExporter excelExporter = new ExcelExporter();
    excelExporter.ExportToExcel(searchResult, response);
}

In my ExportToExcel method I generate the xls file and then I add http headers to download the file.

// excelFileBytes is a byte array holding the data to be written
if (excelFileBytes != null)
{
    response.Clear();
    response.ContentType = "application/octet-stream";
    response.AddHeader("content-disposition", string.Format("attachment; filename=\"{0}\"", fileName));
    response.Flush();
    response.BinaryWrite(excelFileBytes);
    response.Flush();
    response.End();
}

I know that my code is working, but calling it from Ajax did not initiate the download. Here is the response I get (by FireBug in Mozilla Firefox):

enter image description here

How to initiate file download from Ajax?

George Findulov
  • 769
  • 6
  • 16
  • 1
    Is there a question? – cdsln Jul 21 '15 at 10:36
  • Yep, that looks like a ZIP archive (leading `PK` characters) of some XML files (hopefully obvious), which is what a modern Office XML file is. So, the server code seems fine. – Damien_The_Unbeliever Jul 21 '15 at 10:41
  • 1
    However, reading your question again, I realise that your client side code may be doomed. If you search for `ajax trigger download`, you should find plenty of results explaining why it doesn't work. – Damien_The_Unbeliever Jul 21 '15 at 10:44

2 Answers2

0

It's a bit unclear, what you are trying to do, but if I understand you right, you want to initiate a file download without the browser opening a new tab etc.

You should be able to do this using

<a href="/link/to/file" download>anchor text</a>

"download" attribute might not be necessary due to your content-disposition: attachment header.

-1

Try something like this from client side, if you are using jquery

" $("form action='" + downloadUrl + "' method='post'> /form>").appendTo(document.body).submit() ";

Akhil B
  • 40
  • 8