Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC: Downloading an excel file

I'm downloading an excel file within C# action method the reutrns a FileResult, like this:

return File(bindata, "application/octet-stream", "mytestfile.xls");

When I manually navigate to the URL that corresponds with the above method, then I get the rendered out representation of the file. The file will not download with a Save As -dialog.

Is there a way to force the download to happen through Save As -dialog?

-pom-

like image 375
Pompair Avatar asked Sep 12 '11 16:09

Pompair


People also ask

How can I Download Excel file in ASP.NET MVC?

Step 1: Create a new ASP.NET web application project. Step 2: Complete the New ASP.NET Web Application – CreateXlsIOSample dialog: Select MVC. Click OK.

How can I Download Excel file using jQuery in MVC?

Ajax call to action method from button click. Return a file from the action method. Create a blob for excel file and make it auto downloadable using jQuery. Display a loader while processing to generate excel file and download it using jQuery.


3 Answers

Normally when you specify a filename to the File method it automatically appends a Content-Disposition header so that the Save-As dialog always shows. So I am a bit surprised when you say that your code doesn't work. You could also try to manually set this header:

Response.AppendHeader("Content-Disposition", "attachment; filename=mytestfile.xls");
like image 111
Darin Dimitrov Avatar answered Sep 21 '22 10:09

Darin Dimitrov


I have a feeling you are getting this behavior because of the media type you are returning.

Try changing the media type to application/vnd.ms-excel like this:

return File(bindata, "application/vnd.ms-excel", "mytestfile.xls");
like image 22
nikmd23 Avatar answered Sep 18 '22 10:09

nikmd23


Can you try this:

return new FileContentResult(bindata, "application/vnd.ms-excel")
            {
                FileDownloadName = "mytestfile.xls")
            };

Hope this helps.

like image 37
alexl Avatar answered Sep 18 '22 10:09

alexl