Mail Merge using the Open XML SDK

Charlotte Skardon picture Charlotte Skardon · Mar 31, 2009 · Viewed 7.5k times · Source

I have a DataTable with 3 columns (a,b,c) and a docx file with the corresponding MailMerge fields set up. What I'd like to do is perform a Mail Merge on the document with the data.

Presume that you can write to the hard disk (if you need to create a csv etc for doing the merge etc), you don't have word, excel etc, Open XML SDK is installed, but equally we can install anything else.

In terms of the answer, converting the input data to whatever is needed isn't really a problem, the problem is how to perform a mail merge in the Open XML SDK (or other FREE API).

As a side note, the output should be one file with n pages (where n is the number of rows in the data), i.e. not n documents (though I don't mind if the merge of documents is done at the end).

(I should add, I'm not tied to the MailMerge concept, being able to just do a replace for example would work - though obviously that then requires merging the files together at the end...)

Answer

Charlotte Skardon picture Charlotte Skardon · May 22, 2009

I've got this working in a pretty horrible way - basically - at the moment, the algorithm follows this:

  1. Unzip docx file
  2. Read in document.xml (to a string)
  3. string.Replace the fields
  4. Rezip to temporary docx
  5. Merge all the temporary documents created

The actual code for merging the documents comes from Eric White's Blog : http://blogs.msdn.com/ericwhite/archive/2009/02/05/move-insert-delete-paragraphs-in-word-processing-documents-using-the-open-xml-sdk.aspx