sâmbătă, 5 martie 2011

Merging 2 word 2007(open xml) documents

I had to merge 2 word documents once.
They were both in word 2007(open xml) format.
I searched online everywhere for a way to merge them.
All the links were about using the altChunk element. I have a problem with that. The entire document gets put in there and that is a lot of unneeded data(like header and footer etc.).

So I did it another way:
1. cloned the second document's body
2. cloned all it's children and added them to the first document's main part


static void MergeDocs(string doc1Path,string doc2Path)
{
using (var doc2FileStream = File.Open(doc2Path, FileMode.Open))
{
using (WordprocessingDocument doc2 = WordprocessingDocument.Open(doc2FileStream, true))
{
var doc2Body = (Body)doc2.MainDocumentPart.Document.Body.CloneNode(true);
using (var doc1FileStream = File.Open(doc1Path, FileMode.Open))
{
using (WordprocessingDocument doc1 = WordprocessingDocument.Open(doc1FileStream, true))
{
var mainPart = doc1.MainDocumentPart;
foreach (var elem in doc2Body.ChildElements)
{
if (!(elem is SectionProperties))
mainPart.Document
.Body
.InsertAfter(elem.CloneNode(true), mainPart.Document.Body.Elements<paragraph>().Last());
}
mainPart.Document.Save();
}
}
}
}
}
view raw MergeDocs hosted with ❤ by GitHub

2 comentarii:

  1. Thank you so much for that code-snippet. I was looking for exactly that!
    Mike from Germany

    RăspundețiȘtergere
  2. one more thing:
    it should read:
    (with a large capital in "Paragraph"

    .InsertAfter(elem.CloneNode(true), mainPart.Document.Body.Elements().Last());

    Thanx again!

    Mike

    newsmailerformike [at] mail-4-you.de

    RăspundețiȘtergere