2014-02-28 54 views
6

我想返回一個openXML spreadsheetdocument作爲一個字節[],然後我可以使用它來允許我的MVC發送該文件給用戶。這裏是我的spreadsheetdocument方法返回的字節數組openXML spreadsheetdocument爲MVC文件下載返回字節數組

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

的文件下載,但是當你去打開它顯示的錯誤消息該文件已損壞。有沒有其他方法可以讓他們下載這個文件?

+0

你有沒有單獨檢查生成的文件?我的意思是,當你將它保存在「mem.ToArray()」位置的磁盤上時,你的文件是否正確打開?我認爲生成的文件應該存在問題,而不是您將其返回給客戶端的方式。 –

回答

0

我有一個Word文檔的類似問題。我解決了這個使用字節數組outsite的使用,如:


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

return returnBytes; 
+1

我仍然收到「excel發現無法讀取的內容」我點擊yes來恢復內容,然後顯示「工作簿無法打開或由Microsoft Excel修復,因爲它已損壞」,我甚至停止填充電子表格,因此它完全空,但仍然得到「是腐敗」 – Canvas