openXML spreadsheetdocument return byte array for MVC file download

Canvas picture Canvas · Feb 28, 2014 · Viewed 15.4k times · Source

I'm trying to return a openXML spreadsheetdocument as a byte[] which I can then use to allow my MVC to send that file to a user. here is my spreadsheetdocument method to return the byte array

using (MemoryStream mem = new MemoryStream())
{
    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());

    SheetData sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();

    //row start
    for (int id = 0; id <= reports.Count(); id++)
    {
        if (id == 0)
        {
            Row contentRow = CreateContentRow(reports.ElementAt(id), true, 2 + id);
            sheetData.AppendChild(contentRow);
        }
        else
        {
            Row contentRow = CreateContentRow(reports.ElementAt((id - 1)), false, 2 + id);
            sheetData.AppendChild(contentRow);
        }
    }

    // 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();
    return mem.ToArray();
}

then in my MVC controller i call it like this

return File(crs.CreateReportSpreadSheet(reports),"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Reports.xlsx");

the file downloads, but when you go to open it shows an error message that the file is corrupted. Is there any other way to allow them to download this file?

Answer

World Wide DBA picture World Wide DBA · Jul 16, 2014

I know that this is late, but I believe it is because you are not calling close on your spreadsheet document after you are finished with it. Make sure you close the document before returning the memory stream to commit all underlying streams used by the document.

// code omitted for clarity...
workbookpart.Workbook.Save();
spreadsheetDocument.Close();
return mem.ToArray()

http://msdn.microsoft.com/en-gb/library/documentformat.openxml.packaging.spreadsheetdocument(v=office.14).aspx