openXML spreadsheetdocument返回字节数组,用于MVC文件下载

时间:2014-02-28 17:01:37

标签: c# asp.net-mvc asp.net-mvc-4 openxml openxml-sdk

我正在尝试将openXML电子表格文档作为byte []返回,然后我可以使用它来允许我的MVC将该文件发送给用户。这是我的spreadsheetdocument方法返回字节数组

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();
}

然后在我的MVC控制器中我称之为

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

文件下载,但是当你打开它时会显示一条文件已损坏的错误消息。有没有其他方法可以让他们下载这个文件?

2 个答案:

答案 0 :(得分:12)

我知道这已经很晚了,但我相信这是因为您在完成电子表格文档后并没有在电子表格文档中调用。确保在返回内存流之前关闭文档以提交文档使用的所有基础流。

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

答案 1 :(得分:0)

我在Word文档中遇到了类似的问题。我通过使用字节数组outsite来解决这个问题,如:


byte[] returnBytes = null;
using (MemoryStream mem = new MemoryStream())
  {
    // your code
    returnBytes = mem.ToArray();
  }

return returnBytes;