Search code examples
asp.net-mvcexport-to-excel

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");
}

Solution

  • 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");