2012-12-14 99 views
0

我試圖做到這一點對ASP.NET MVC 4:流Word文檔的OpenXML的SDK得到腐敗的文件

MemoryStream mem = new MemoryStream(); 
     using (WordprocessingDocument wordDoc = 
      WordprocessingDocument.Create(mem, DocumentFormat.OpenXml.WordprocessingDocumentType.Document, true)) 
     { 
      // instantiate the members of the hierarchy 
      Document doc = new Document(); 
      Body body = new Body(); 
      Paragraph para = new Paragraph(); 
      Run run = new Run(); 
      Text text = new Text() { Text = "The OpenXML SDK rocks!" }; 

      // put the hierarchy together 
      run.Append(text); 
      para.Append(run); 
      body.Append(para); 
      doc.Append(body); 

      //wordDoc.Close(); 

      ///wordDoc.Save(); 
     } 


return File(mem.ToArray(), "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "ABC.docx"); 

然而ABC.docx打開爲損壞並且止跌」即使修復後也不會打開。

任何想法?

鏈接Qs的:

Streaming In Memory Word Document using OpenXML SDK w/ASP.NET results in "corrupt" document

回答

4

顯然,問題來自缺少這2條線:

wordDoc.AddMainDocumentPart(); 
wordDoc.MainDocumentPart.Document = doc; 

更新的代碼下面,現在完美的作品,即使沒有任何額外的潮紅,等等。

MemoryStream mem = new MemoryStream(); 
     using (WordprocessingDocument wordDoc = 
      WordprocessingDocument.Create(mem, DocumentFormat.OpenXml.WordprocessingDocumentType.Document, true)) 
     { 
      wordDoc.AddMainDocumentPart(); 
      // instantiate the members of the hierarchy 
      Document doc = new Document(); 
      Body body = new Body(); 
      Paragraph para = new Paragraph(); 
      Run run = new Run(); 
      Text text = new Text() { Text = "The OpenXML SDK rocks!" }; 

      // put the hierarchy together 
      run.Append(text); 
      para.Append(run); 
      body.Append(para); 
      doc.Append(body); 
      wordDoc.MainDocumentPart.Document = doc; 
      wordDoc.Close(); 
     } 
return File(mem.ToArray(), "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "ABC.docx"); 
相關問題