Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC - Download Excel file from MemoryStream (Corrupt file)

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 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.

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

Code

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");
like image 456
Detilium Avatar asked Mar 04 '16 07:03

Detilium


Video Answer


2 Answers

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");
like image 107
Mikhail Tulubaev Avatar answered Sep 21 '22 16:09

Mikhail Tulubaev


I think you should return byte array rather than stream. Try using this approach. (This example uses ClosedXML)

 byte[] xlsInBytes;
 using (MemoryStream ms = new MemoryStream())
 {
      workbook.SaveAs(ms);
      xlsInBytes = ms.ToArray();
 }

 return File(xlsInBytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Report.xlsx");
like image 22
Anton Avatar answered Sep 21 '22 16:09

Anton