Darren Young
Darren Young

Reputation: 11090

ASP.net MVC Downloading Excel

I have managed to create the Excel file using HTMLTextwriter, but the returned file is into a Javascript function.

The view code is:

<input type="submit" id = "exportExcelBtn" class = "searchButton" value="Export To Excel" 
onclick= "ExportToExcel();"/>

The JS function then gets the data required for the control action, and then calls the relevant action, as such:

$.ajax({
    type: "GET",
    url: "/Search/ExportToExcel",
    data: { //parameters        },
    error: function (error) {
        alert(error.responseText);
    },
    success: function (data) {
        alert("success");
        alert(data);
    }
});

The Excel file is created, by deriving from ActionResult, and returned back to the JS method. The created Excel file is written to the browser as such:

HttpContext context = HttpContext.Current;
            context.Response.Clear();

            context.Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
            context.Response.Charset = "";

            context.Response.Cache.SetCacheability(HttpCacheability.NoCache);

            context.Response.ContentType = contentType;
            context.Response.Write(content);
            context.Response.End();

How then can I get that file downloaded to the users computer?

I can easily just use File.WriteAllText in the model method, but I feel that is cheating the MVC method?

Upvotes: 2

Views: 12043

Answers (2)

Zruty
Zruty

Reputation: 8667

You are sending the Excel file itself as a response to an AJAX request. This will require JavaScript to recognize and parse the file, and, more importantly, to save it to disk. This is inappropriate (and, probably, impossible).

I recommend you to get rid of AJAX, and open the link /Search/ExportToExcel in another browser window. Then the browser (not your JS, but the browser) will be receiving the file and saving it.

Upvotes: 3

SLaks
SLaks

Reputation: 887413

You can't use File.WriteAllText in the model.
That will write it to the server.

You need to set the location to a URL that returns the contents of the Excel file.
The correct way to do that in MVC is to return File(content,"application/x-ms-excel", fileName)

Upvotes: 3

Related Questions