2014-02-18 81 views
2

我想用Open XML SDK 2.5從ASP.NET MVC4導出一個Excel表。我試圖使用從MSDN標準的例子,從ASP.NET MVC創建開放的XML Excel表時出錯

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

我的文件被下載得到,但是當我嘗試打開它,擅長流行音樂是一個錯誤,指出該文件已損壞。當我用記事本或記事本++打開文件時,文件完全是空的,並且其中沒有xml數據。

我在想什麼,需要做什麼?

在此先感謝。

+0

是你事後調用response.Flush()? – rla4

+0

是的,我正在調用flush。像trailmax提到的問題是SEEK。 – Yogesh

回答

3

嘗試重置內存流位置設置爲0,你把它複製到響應之前:

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

或者以複製內存流來響應,你可以從你的MVC行動回報FileStreamResult

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