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?
One reason that you might be getting this problem is that the
filehere is at the end of the stream:I suggest you set to 0:
Your previous code works since you use
str.WriteTowhich ignores the current position.