Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exporting Excel File to View (MVC)

I have to Export Data to View as Excel , Actually I have Implemented,but my doubt is when to use

return new FileContentResult(fileContents, "application/vnd.ms-excel");

vs

return File(fileContents, "application/vnd.ms-excel");

and How can set Downloadable Filename in each of this methods?

Example 1:

public ActionResult ExcelExport()
{
   byte[] fileContents = Encoding.UTF8.GetBytes(data);
   return new FileContentResult(fileContents, "application/vnd.ms-excel");
}

Example:2

public ActionResult ExcelExport()
{
   byte[] fileContents = Encoding.UTF8.GetBytes(data);
   return File(fileContents, "application/vnd.ms-excel");
}
like image 320
Tom Crusie Avatar asked Oct 01 '11 23:10

Tom Crusie


1 Answers

You can read about the differences between FileContentResult & FileResult here : What's the difference between the four File Results in ASP.NET MVC

You can specify the filename like this

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

// or

// note that this call will return a FileContentResult object
return new File(fileContents, "application/vnd.ms-excel", "name.xls");
like image 146
Steven K. Avatar answered Sep 18 '22 10:09

Steven K.