title: Merging Documents with Open XML
body: <p>I am looking for mail merge alternatives in my vb.net app.  I have used the mail merge feature of word, and find that it is quite buggy when dealing with a large volume of documents.  I am looking at alternate methods of generating the merge, and have come across open xml.  I think this will probably be the answer I am looking for.  I have come to understand that the merge will be entirely code-driven in vb.net.  I have started playing around with the following code:</p>
  
  <pre><code>Dim wordprocessingDocument As WordprocessingDocument = wordprocessingDocument.Open("C:\Users\JasonB\Documents\test.docx", True)
  
      'for each simplefield (mergefield)
      For Each field In wordprocessingDocument.MainDocumentPart.Document.Body.Descendants(Of SimpleField)()
          'get the document instruction values
          Dim instruction As String() = field.Instruction.Value.Split(splitChar, StringSplitOptions.RemoveEmptyEntries)
  
  
          'if mergefield
          If instruction(0).ToLower.Equals("mergefield") Then
  
              Dim fieldname As String = instruction(1)
  
  
             For Each fieldtext In field.Descendants(Of Text)()
                  fieldtext.Text = "I AM TESTING"
              Next
  
          End If
  
          wordprocessingDocument.MainDocumentPart.Document.Save()
          wordprocessingDocument.Dispose()
  </code></pre>
  
  <p>Now this works great and all, but I am realizing that I need to create as many documents as I will have datarows (assuming I use a datatable to handle the data).</p>
  
  <p>One suggestion I found was to loop through each datarow, take my document template, save it to a folder and insert the datarow data. This could mean however that I end up with 12,000 documents in a single folder that need to be joined later and converted to pdf.</p>
  
  <p>Is there another option?  The other thing that stood out to me is to create a new word document, and duplicate over the xml from the template, and then replace the values.  I dont know however if there is a "simpler" way of doing this, thanks. </p>