This is exactly what I need, thank you! I spent the day on google looking literally at hundreds of searches for "mail merge vb.net sql server" I'll be doing my searching more here, Thanks again!
Sorry to bump such an old thread, but stumbled across this the other day, and it works almost how I want it. One thing I cannot work out though, is if the the sql statement needs to bring back the fields in the same order as the mail merge fields within the word document?
My merge is working to an extent, but puts the fields from the dataset in to random merge fields, not the correct ones.
Any ideas?
Also, the above example creates a new word document for each record, ideally I would like to insert a new page for each row, instead of a new document. Any ideas on that one? I spent the entirety of yesterday trying ways to insert a page break, but no luck.
Sorry to bump such an old thread, but stumbled across this the other day, and it works almost how I want it. One thing I cannot work out though, is if the the sql statement needs to bring back the fields in the same order as the mail merge fields within the word document?
My merge is working to an extent, but puts the fields from the dataset in to random merge fields, not the correct ones.
Any ideas?
Also, the above example creates a new word document for each record, ideally I would like to insert a new page for each row, instead of a new document. Any ideas on that one? I spent the entirety of yesterday trying ways to insert a page break, but no luck.
Thanks
Looking at the code:
Code:
For Each MergeField As Word.MailMergeField In moApp.ActiveDocument.MailMerge.Fields
'Select the text
MergeField.Select()
'Type the text
moApp.Selection.TypeText(Convert.ToString(row(intCount)))
intCount += 1
Next
It is assuming that the mergefields will be in the same order as the columns of the datatable. In your case, this is most likely not so. What you should probably do is keep the data table column names the same as the merge field names, then inside the mergefield loop above, get the string name of the mergefield after Mergefield.Select() occurs, match it to the string name column in the datatable, then assign that value using .TypeText()
The example on this forum thread is using Interop, which can cause trouble in server-side application (see Microsoft's KB 257757).
My advice would be to use fully managed .NET solution with OpenXML. Since OpenXML has steep learning curve, it would probably make sense to look for a toolkit which uses that kind of approach.
I have good experience with Docentric Toolkit. I have been using it for three years now. So here are its pros and cons:
Pros:
- plain simple Word Add-in for template generation
- OpenXML based, server side friendly
- support for images, data-bound graphs, tables
- conditional elements in templates
- support for placeholders in headers and footers
- very fast report generation
Cons:
- not free
- support for PDF output is still somewhat limited.