簡體   English   中英

使用OpenXML和XElement將多個Word文檔合並為一個

[英]Merge multiple word documents into one using OpenXML and XElement

如標題所示,我正在嘗試將多個word(.docx)文件合並為一個word 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();
}

同樣的問題是,每個新創建的文檔都具有與第一個文檔相同的內容。 因此,當我運行此命令時,輸出將是一個具有五個相同頁面的文檔。 我嘗試過切換列表中的文檔順序,並得到相同的結果,因此它並不只針對一個文檔。 有人可以建議我在這里做錯了嗎? 我正在瀏覽它,無法解釋我所看到的行為。 任何建議,將不勝感激。 非常感謝!

編輯:我認為這可能與以下事實有關:我嘗試合並的文檔已使用自定義XML部件生成。 我認為文檔中的Xpath以某種方式指向相同的內容。 關鍵是我可以打開每個文檔並查看正確的內容,只是在合並它們時才看到問題。

您似乎合並的方式有時可能無法正常工作。 您可以嘗試其中一種方法

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

    如果仍然遇到類似的問題,則可以在合並之前找到數據綁定控件,然后從CustomXml部分將數據分配給這些控件。 您可以在OpenXmlHelper類的方法AssignContentFromCustomXmlPartForDataboundControl中找到此方法。 可以從http://worddocgenerator.codeplex.com/下載該代碼

此解決方案使用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();
            }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM