使用OpenXML和XElement将多个word文档合并为一个

The*_*hod 5 c# xml linq ms-word openxml

正如标题所述,我试图将多个单词(.docx)文件合并为一个单词doc.这些文件中的每一篇都是一页长.我在这个实现中使用了这篇文章中的一些代码.我遇到的问题是只有第一个文档被正确编写,每个其他迭代都附加一个新文档,但文档内容与第一个相同.

这是我正在使用的代码:

//list that holds the file paths
List<String> fileNames = new List<string>();
fileNames.Add("filePath");
fileNames.Add("filePath");
fileNames.Add("filePath");
fileNames.Add("filePath");
fileNames.Add("filePath");

//get the first document
MemoryStream mainStream = new MemoryStream();
byte[] buffer = File.ReadAllBytes(fileNames[0]);
mainStream.Write(buffer, 0, buffer.Length);

using (WordprocessingDocument mainDocument = WordprocessingDocument.Open(mainStream, true))
{
    //xml for the new document
    XElement newBody = XElement.Parse(mainDocument.MainDocumentPart.Document.Body.OuterXml);
    //iterate through eacah file
    for (int i = 1; i < fileNames.Count; i++)
    {
        //read in the document
        byte[] tempBuffer = File.ReadAllBytes(fileNames[i]);
        WordprocessingDocument tempDocument = WordprocessingDocument.Open(new MemoryStream(tempBuffer), true);
        //new documents XML
        XElement tempBody = XElement.Parse(tempDocument.MainDocumentPart.Document.Body.OuterXml);
        //add the new xml
        newBody.Add(tempBody);
        string str = newBody.ToString();
        //write to the main document and save
        mainDocument.MainDocumentPart.Document.Body = new Body(newBody.ToString());
        mainDocument.MainDocumentPart.Document.Save();
        mainDocument.Package.Flush();
        tempBuffer = null;
    }
    //write entire stream to new file
    FileStream fileStream = new FileStream("xmltest.docx", FileMode.Create);
    mainStream.WriteTo(fileStream);
    //ret = mainStream.ToArray();
    mainStream.Close();
    mainStream.Dispose();
}
Run Code Online (Sandbox Code Playgroud)

同样问题是,正在创建的每个新文档都具有与第一个文档相同的内容.所以当我运行它时,输出将是一个包含五个相同页面的文档.我已经尝试在列表中切换文档顺序并获得相同的结果,因此它不是一个文档特定的.谁能提出我在这里做错了什么?我正在浏览它,我无法解释我所看到的行为.任何建议,将不胜感激.非常感谢!

编辑:我认为这可能与我试图合并的文档是使用自定义XML部分生成的事实有关.我认为文档中的Xpath以某种方式指向相同的内容.问题是我可以打开这些文档中的每一个并看到正确的内容,就在我合并它们时,我看到了问题.

Ema*_*eco 5

该解决方案使用DocumentFormat.OpenXml

public static void Join(params string[] filepaths)
    {

     //filepaths = new[] { "D:\\one.docx", "D:\\two.docx", "D:\\three.docx", "D:\\four.docx", "D:\\five.docx" };
        if (filepaths != null && filepaths.Length > 1)

            using (WordprocessingDocument myDoc = WordprocessingDocument.Open(@filepaths[0], true))
            {
                MainDocumentPart mainPart = myDoc.MainDocumentPart;

                for (int i = 1; i < filepaths.Length; i++)
                {
                    string altChunkId = "AltChunkId" + i;
                    AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(
                        AlternativeFormatImportPartType.WordprocessingML, altChunkId);
                    using (FileStream fileStream = File.Open(@filepaths[i], FileMode.Open))
                    {
                        chunk.FeedData(fileStream);
                    }
                    DocumentFormat.OpenXml.Wordprocessing.AltChunk altChunk = new DocumentFormat.OpenXml.Wordprocessing.AltChunk();
                    altChunk.Id = altChunkId;
                    //new page, if you like it...
                        mainPart.Document.Body.AppendChild(new Paragraph(new Run(new Break() { Type = BreakValues.Page })));
                    //next document
                    mainPart.Document.Body.InsertAfter(altChunk, mainPart.Document.Body.Elements<Paragraph>().Last());
                }
                mainPart.Document.Save();
                myDoc.Close();
            }
    }
Run Code Online (Sandbox Code Playgroud)


小智 3

您似乎合并的方式有时可能无法正常工作。您可以尝试其中一种方法

  1. 使用 AltChunk,如http://blogs.msdn.com/b/ericwhite/archive/2008/10/27/how-to-use-altchunk-for-document- assembly.aspx

  2. 使用http://powertools.codeplex.com/DocumentBuilder.BuildDocument方法

    如果您仍然面临类似的问题,您可以在合并之前找到数据绑定控件,并将数据从 CustomXml 部分分配给这些控件。您可以在 OpenXmlHelper 类的方法AssignContentFromCustomXmlPartForDataboundControl 中找到此方法。代码可以从http://worddocgenerator.codeplex.com/下载