I have the following action inside my Controller
public ActionResult DownloadExcel()
{
//create and populate Excel file here
C1XLBook testBook = new C1XLBook();
//populate it here
MemoryStream ms = new MemoryStream();
testBook.Save(ms, FileFormat.Biff8);
return File(ms, "application/ms-excel", "test-file.xls");
}
When opening the file, I get the Excel message saying that the file doesn’t match the extension and the file opens up corrupted.
If I save the file on the hard drive and return it from there, everything is fine:
return base.File(@"C:\LOGS\test-file.xls", "application/ms-excel", "test-excel.xls");
I initially thought that the Save function corrupts it when saving it into the MemoryStream, so I saved and re-loaded it back and it was fine passing back to the user – when saved on the Hard Drive and returned from there, rather than from the MemoryStream
Any ideas? I am not too fond of saving the file on the Hard Drive….besides I should be able to save it into the MemoryStream and return it from there?
One hunch I have is that perhaps the MemoryStream should not be used to return files in MVC, since every request is isolated?
Perhaps you need to rewind the memory stream (set
ms.Position = 0;) before passing it to the result? After the call toSaveits position will be at the end, not the beginning.