2012-08-13 55 views
2

我有一個文檔,我通過獲取段落進行迭代。對於這些段落中的每一段,我需要創建一個新文檔並保存它。我無法弄清楚如何將源文檔中的段落添加到新文檔中。打開Xml:Word創建一個新的文檔並從另一個文檔添加一個段落

 foreach (var p in paragraphsFromSourceDocument) 
     { 
      using (var memoryStream = new MemoryStream()) 
      { 
       var doc = WordprocessingDocument.Create(memoryStream, WordprocessingDocumentType.Document); 
       doc.AddMainDocumentPart(); 

       // Create the Document DOM. 
       doc.MainDocumentPart.Document = new Document(); 
       doc.MainDocumentPart.Document.Body = new Body(); 

       //Add the paragraph 'p' to the Body here: 
       // HOW ????????? 

       doc.MainDocumentPart.Document.Save(); 
      } 
     } 

回答

4
// Open the file read-only since we don't need to change it. 
     using (var wordprocessingDocument = WordprocessingDocument.Open(documentFileName, true)) 
     { 
      paragraphs = wordprocessingDocument.MainDocumentPart.Document.Body 
       .OfType<Paragraph>().ToList(); 
      styles = wordprocessingDocument.MainDocumentPart.StyleDefinitionsPart; 

      foreach (var p in paragraphs) 
      { 
       using (var memoryStream = new MemoryStream()) 
       { 
        var doc = WordprocessingDocument.Create(memoryStream, WordprocessingDocumentType.Document); 
        doc.AddMainDocumentPart().AddPart(styles); 
        doc.MainDocumentPart.Document = new Document(); 
        doc.MainDocumentPart.Document.Body = new Body(); 
        doc.MainDocumentPart.Document.Body.Append(p.CloneNode(true)); 
        doc.MainDocumentPart.Document.Save(); 
        Console.WriteLine(GetHTMLOfDoc(doc)); 

       } 
      } 
     } 
相關問題