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

时间:2012-07-23 15:36:37

标签: c# xml linq ms-word openxml

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

以下是我正在使用的代码:

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

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

编辑:我认为这可能与我尝试合并的文档是使用自定义XML部件生成的事实有关。我认为文档中的Xpath以某种方式指向相同的内容。问题是我可以打开这些文档并看到正确的内容,只有当我合并它们时才能看到问题。

2 个答案:

答案 0 :(得分:3)

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

  1. http://blogs.msdn.com/b/ericwhite/archive/2008/10/27/how-to-use-altchunk-for-document-assembly.aspx
  2. 中使用AltChunk
  3. 使用http://powertools.codeplex.com/ DocumentBuilder.BuildDocument方法

    如果您仍然遇到类似的问题,可以在Merge和之前找到数据绑定控件 从CustomXml部件为这些控件分配数据。您可以在OpenXmlHelper类的AssignContentFromCustomXmlPartForDataboundControl方法中找到此方法。代码可以从http://worddocgenerator.codeplex.com/

  4. 下载

答案 1 :(得分:2)

此解决方案使用 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();
            }
    }
相关问题