asp.net-mvc 导出 Excel 文件以查看 (MVC)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7623599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 01:29:57  来源:igfitidea点击:

Exporting Excel File to View (MVC)

asp.net-mvcexport-to-excel

提问by Tom Crusie

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

我必须将数据导出到 Excel 中查看,实际上我已经实现了,但我怀疑什么时候使用

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:

示例 1:

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

Example:2

示例:2

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

回答by Steven K.

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

您可以在此处阅读 FileContentResult 和 FileResult 之间的区别: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");