c# - ASP.NET MVC - 从 MemoryStream 下载 Excel 文件(损坏的文件)

标签 c# asp.net asp.net-mvc excel

我正在尝试使用浏览器中的内置下载来下载 Excel 文件。基本上下载工作正常,在我的 Controller 中创建了 Excel 文件之后,但是当我试图在 Excel 中打开这个文件时,我被告知文件已损坏:

Excel cannot open the file 'Report.xlsx' because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file.

当强制在 Excel 中打开文件时,工作表只是空的。我不知道这是为什么。

代码

我没有展示我是如何创建 Excel 文件的,因为那是无关紧要的(在使用内存流之前它运行良好)。

var stream = wBook.WriteXLSX(); // Return a MemoryStream (Using DTG.Spreadsheet)

return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Report.xlsx");

最佳答案

您应该将当前流位置设置为 0 以成功导出您的文件。

var stream = wBook.WriteXLSX(); // Return a MemoryStream (Using DTG.Spreadsheet)

stream.Seek(0, SeekOrigin.Begin);

return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Report.xlsx");

关于c# - ASP.NET MVC - 从 MemoryStream 下载 Excel 文件(损坏的文件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35790721/

相关文章:

c# - wpf 绑定(bind)到客户端不显示名称

c# - 如何以编程方式判断是否在 .NET ListView 中单击了组 header ?

c# - Azure 网站中的站点无法处理 X509Certificate2

javascript - Breezejs 实体、 knockout 绑定(bind)、空导航属性

css - MVC5 Razor Response.Write - 文本位置

c# - 堆栈推送和弹出

c# - 在其他选项 services.Configure<>() 内绑定(bind)选项

asp.net - CA 服务台 Web 服务视觉基础专家

ASP.NET MVC 应用程序设置 loginUrl 接受

asp.net - 如何在asp中填充图像和文本:Menu control