ASP.NET MVC-从MemoryStream下载Excel文件(损坏的文件) [英] ASP.NET MVC - Download Excel file from MemoryStream (Corrupt file)

查看:352
本文介绍了ASP.NET MVC-从MemoryStream下载Excel文件(损坏的文件)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to make an Excel file download using the in-build downloading in browsers. Basically the download is working fine, after I've created the Excel file within my controller, but when I'm trying to open this file in Excel, I'm told that the file is corrupted:

Excel无法打开文件'Report.xlsx',因为文件格式或文件扩展名无效.确认文件未损坏,并且文件扩展名与文件格式匹配.

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中打开文件时,工作表只是空的.我不知道为什么会这样.

When forcing the file to open in Excel, the sheet is simply empty. I have no idea why this is.

代码

我没有显示我如何创建Excel文件,因为这是无关紧要的(在使用内存流之前工作正常).

I'm not showing how I'm creating the Excel file, as that's irrelevant (it worked fine before using memory stream).

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

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

推荐答案

您应将当前流位置设置为0,以成功导出文件.

You should set current stream position to 0 to successfully export your file.

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

这篇关于ASP.NET MVC-从MemoryStream下载Excel文件(损坏的文件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆