MS Word mail merge automation

Steve M sjmaster at gmail.com
Wed Oct 5 14:25:56 EDT 2005


I was finally able to get things working right, so I thought I'd stick
an example here for posterity.

"""An example of a MS Word mail merge using the COM interface.
In order for this script to work you must first run the COM Makepy
utility and select
"Microsoft Word 10.0 Object Library (8.2)" or whatever your version of
Word is.
The template must also be set up with merge fields corresponding to the
data source.
"""
import os, win32com.client

doc_template_name = os.path.abspath('template.doc')
data_source_name = os.path.abspath('record23.csv')
doc_final_name = os.path.abspath('record23.doc')

app = win32com.client.Dispatch("Word.Application")
doc_template = app.Documents.Open(doc_template_name)

mm = doc_template.MailMerge

#attach data source to template
mm.OpenDataSource(data_source_name)

#merge just one record - this step may be redundant
mm.DataSource.FirstRecord = 1
mm.DataSource.LastRecord = 1

#send the merge result to a new document
mm.Destination = win32com.client.constants.wdSendToNewDocument

#merge
mm.Execute()

#apparently app.Documents is like a stack
doc_final = app.Documents[0]

#save our new document
doc_final.SaveAs(doc_final_name)

#cleanup
doc_final.Close()
doc_template.Close()
app.Quit()




More information about the Python-list mailing list