7

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");
3
  • 1
    Show the code for WriteXLSX please. Commented Mar 4, 2016 at 7:52
  • 1
    My guess is that you're returning a stream which is positioned at the end, and you just need to add stream.Position = 0; within WriteXLSX - but as Alexander says, we can't tell without seeing it. Commented Mar 4, 2016 at 7:56
  • The WriteXLSX is a method from the library Commented Mar 4, 2016 at 8:00

2 Answers 2

18

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");
Sign up to request clarification or add additional context in comments.

4 Comments

This one did it for me. Appreciate the assistance.
@Detilium may I know what dll you are using for this line wBook.WriteXLSX()?
@AljohnYamaro I'm pretty sure it was this one systemexplorer.net/file-database/file/dtg.spreadsheet-dll. Though it's been over 2 years since this SO
Jesus H Christ, this bug haunted me for a week. I dont know how I didnt see this answer until now but it worked for me. Thanks dude.
4

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");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.