打开Xml:Word创建一个新文档并从另一个文档添加一个段落

时间:2012-08-13 21:37:08

标签: openxml openxml-sdk

我有一个文件,我通过获取段落迭代。对于每个段落,我需要创建一个新文档并保存。我无法弄清楚如何将源文档中的段落添加到新文档中。

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

1 个答案:

答案 0 :(得分: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));

                }
            }
        }