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");
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");
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With