在 MVC 2 中将流作为附件发送到浏览器
我正在尝试在 MVC 2 中实现 Open XML Excel 电子表格的文件下载链接。如果我直接写入响应,它的工作原理如下...
var data = MooseMartAdoManager.ExecuteSet("Report.StagAllCasesFullDetail");
var str = ExcelExportManager.GenerateSpreadsheet(data) as MemoryStream;
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader(
"content-disposition",
"attachment;filename=StagFullDetail" + DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss") + ".xlsx");
str.WriteTo(Response.OutputStream);
但我已经花时间抽象了有关数据如何处理的所有逻辑收集并创建报告以供代码重用和 IOC,如果能够弄清楚为什么这个不起作用......
public FileStreamResult GetExcelDetailExport()
{
var data = MooseMartAdoManager.ExecuteSet("Report.StagAllCasesFullDetail");
var file = ExcelExportManager.GenerateSpreadsheet(data);
return File(file, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"StagFullDetail" + DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss") + ".xlsx");
}
我得到的只是 txt 格式的零字节文件。
那么处理这个问题的“正确”MVC 方法是什么?
I am trying to implement a file download link for an Open XML Excel spreadsheet in MVC 2. If I write directly to the Response it works as below...
var data = MooseMartAdoManager.ExecuteSet("Report.StagAllCasesFullDetail");
var str = ExcelExportManager.GenerateSpreadsheet(data) as MemoryStream;
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader(
"content-disposition",
"attachment;filename=StagFullDetail" + DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss") + ".xlsx");
str.WriteTo(Response.OutputStream);
But seeing as I have taken the time to abstract all logic away about how the data is collected and the report is created for code reuse and IOC, it would be nice to be able to work out why this dosent work...
public FileStreamResult GetExcelDetailExport()
{
var data = MooseMartAdoManager.ExecuteSet("Report.StagAllCasesFullDetail");
var file = ExcelExportManager.GenerateSpreadsheet(data);
return File(file, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"StagFullDetail" + DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss") + ".xlsx");
}
All I get is zero bytes file in txt format.
So what is the "correct" MVC way to handle this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能遇到此问题的原因之一是这里的
file
位于流的末尾:我建议您设置为 0:
您之前的代码可以工作,因为您使用了
str.WriteTo< /code> 忽略当前位置。
One reason that you might be getting this problem is that the
file
here is at the end of the stream:I suggest you set to 0:
Your previous code works since you use
str.WriteTo
which ignores the current position.