Combine .docx Word 2007 documents with the Microsoft Office Open XML SDK 2.0

First install the Microsoft Office Open XML SDK 2.0 (I installed the December 2009 CTP). Now open up Visual Studio 2008, create a project and add a reference to “DocumentFormat.OpenXml” (right click on project -> Add Reference). I also had to add a reference to “WindowsBase” at “C:Program FilesReference AssembliesMicrosoftFrameworkv3.0″.

Now add the following to your “using” statements at the top of your code:

using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using System.IO;
using System.IO.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using System.IO;
using System.IO.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;

Now if you are combining “c:doc1.docx” and “c:doc2.docx” by adding doc2 to the end of doc1 you use the following code:

string doc1 = “c:\1.docx”;
string doc2 = “c:\2.docx”;
using (WordprocessingDocument myDoc = WordprocessingDocument.Open(doc1, true))
{
string altChunkId = “AltChunkId2″;
MainDocumentPart mainPart = myDoc.MainDocumentPart;
AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(
AlternativeFormatImportPartType.WordprocessingML, altChunkId);
using (FileStream fileStream = File.Open(doc2, FileMode.Open))
chunk.FeedData(fileStream);
AltChunk altChunk = new AltChunk();
altChunk.Id = altChunkId;
mainPart.Document.Body.InsertAfter(altChunk, mainPart.Document.Body.Elements<Paragraph>().Last());
mainPart.Document.Save();
}

The end result is all the content of “doc2.docx” neatly inserted at the end of “doc1.docx”.