Question

I am trying to export an Excel sheet from ASP.NET MVC4 using Open XML SDK 2.5. I am trying to use standard example from MSDN,

extention = "xlsx";
response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
response.AddHeader("Content-Disposition",String.Format("attachment; filename={0}.{1}", fileName, extention));
using (MemoryStream mem = new MemoryStream())
{
    // Create a spreadsheet document by supplying the filepath.
    // By default, AutoSave = true, Editable = true, and Type = xlsx.
    SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(mem, SpreadsheetDocumentType.Workbook);

     // Add a WorkbookPart to the document.
     WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
     workbookpart.Workbook = new Workbook();

     // Add a WorksheetPart to the WorkbookPart.
     WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
     worksheetPart.Worksheet = new Worksheet(new SheetData());

     // Add Sheets to the Workbook.
     Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets());

      // Append a new worksheet and associate it with the workbook.
      Sheet sheet = new Sheet()
      {
            Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart),
            SheetId = 1,
            Name = "mySheet"
       };
       sheets.Append(sheet);

       workbookpart.Workbook.Save();

       // Close the document.
       spreadsheetDocument.Close();

       mem.CopyTo(response.OutputStream);
 }

My file is getting downloaded, but when I try to open it, excel pop's an error saying that the file is corrupt. When I open the file with notepad or notepad++ the file is completely empty and there is no xml data in it.

What am I missing and what needs to be done?

Thanks in advance.

Was it helpful?

Solution

Try resetting your memory stream position to zero before you copy it to response:

// Close the document.
spreadsheetDocument.Close();
mem.Position = 0;
mem.CopyTo(response.OutputStream);

Alternatively to copying memory stream to response, you can return FileStreamResult from your MVC Action:

public ActionResult XlsDocument()
{
    // generating your document here...

    // very important to reset memory stream to a starting position, otherwise you would get 0 bytes returned
    memoryStream.Position = 0;

    var resultStream = new FileStreamResult(memoryStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";);
    resultStream.FileDownloadName = String.Format("{0}.{1}", fileName, extension);

    return resultStream;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top