导出Excel文件到视图(MVC)

Tom*_*sie 6 asp.net-mvc export-to-excel

我必须将数据导出为Excel,实际上我已实现,但我怀疑何时使用

return new FileContentResult(fileContents, "application/vnd.ms-excel");
Run Code Online (Sandbox Code Playgroud)

VS

return File(fileContents, "application/vnd.ms-excel");
Run Code Online (Sandbox Code Playgroud)

以及如何在每种方法中设置可下载的文件名?

例1:

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

例如:2

public ActionResult ExcelExport()
{
   byte[] fileContents = Encoding.UTF8.GetBytes(data);
   return File(fileContents, "application/vnd.ms-excel");
}
Run Code Online (Sandbox Code Playgroud)

Ste*_* K. 9

你可以在这里阅读FileContentResult和FileResult之间的差异:ASP.NET MVC中四个文件结果之间的区别是什么

您可以像这样指定文件名

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");
Run Code Online (Sandbox Code Playgroud)