开发者

ASP.net MVC Downloading Excel

开发者 https://www.devze.com 2023-03-21 15:26 出处:网络
I have managed to create the Excel file using HTMLTextwriter, but the returned file is into a Javascript function.

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(H开发者_C百科ttpCacheability.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?


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)


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消