473,320 Members | 1,865 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

MS Word mail merge automation

I'm trying to do invoke the mail merge functionality of MS Word from a
Python script. The situation is that I have a template Word document,
and a record that I've generated in Python, and I want to output a new
Word .doc file with the template filled in with the record I've
generated.

(To refresh your memory, in Word a mailmerge is achieved by a) under
Tools -> Letters and Mailings, check off Show Mail Merge Toolbar; b)
open a document with template-style variables in the form of
<<FIELD_NAME>>; c) on Toolbar select Open Data Source and select
appropriate Access or Excel or CSV file (with column headers
corresponding to the FIELD_NAME's in your template variables); and then
d) on Toolbar select Merge To New Document to create a new document
with the template variables replaced with the value from the
corresponding column in the data source - here, you can make one
document per row of data source, or just one document for a given row.
Don't forget to save the new document.)

Using various online sources*, I have been able to piece together all
but (what I hope is) the final missing piece, viz., the name of the
method that corresponds to "Merge to New Document" command from within
the Word interface.

Here is the basic code, if anyone can provide the missing piece I (and
others, I suspect) would appreciate it:
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 = app.Documents.Open(doc_template_name)

#attach data source to template
doc.MailMerge.OpenDataSource(data_source_name)

#merge to new document - THIS RAISES ATTRIBUTE ERROR, HOW TO FIX?
new_doc = doc.MailMerge.MergeToNewDocument()

#save out result
new_doc.SaveAs(doc_final_name)

#cleanup
doc.Close()
new_doc.Close()
app.Quit()


*I found some information here:
http://64.233.161.104/search?q=cache...document&hl=en

and here:
http://www.brunningonline.net/simon/...es/001299.html

as well as here:
http://www.win32com.de/index.php?opt...=86&Itemid=192

I also have the Hammond and Robinson book on Python on Win32 but it
hasn't helped me to discover the method name.

Sep 30 '05 #1
2 12427

Steve M wrote:
I'm trying to do invoke the mail merge functionality of MS Word from a
Python script. The situation is that I have a template Word document,
and a record that I've generated in Python, and I want to output a new
Word .doc file with the template filled in with the record I've
generated.

(To refresh your memory, in Word a mailmerge is achieved by a) under
Tools -> Letters and Mailings, check off Show Mail Merge Toolbar; b)
open a document with template-style variables in the form of
<<FIELD_NAME>>; c) on Toolbar select Open Data Source and select
appropriate Access or Excel or CSV file (with column headers
corresponding to the FIELD_NAME's in your template variables); and then
d) on Toolbar select Merge To New Document to create a new document
with the template variables replaced with the value from the
corresponding column in the data source - here, you can make one
document per row of data source, or just one document for a given row.
Don't forget to save the new document.)

Using various online sources*, I have been able to piece together all
but (what I hope is) the final missing piece, viz., the name of the
method that corresponds to "Merge to New Document" command from within
the Word interface.

Here is the basic code, if anyone can provide the missing piece I (and
others, I suspect) would appreciate it:
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 = app.Documents.Open(doc_template_name)

#attach data source to template
doc.MailMerge.OpenDataSource(data_source_name)

#merge to new document - THIS RAISES ATTRIBUTE ERROR, HOW TO FIX?
new_doc = doc.MailMerge.MergeToNewDocument()
In VBA, it would be .Execute.
From the VBA Help file:
This example executes a mail merge if the active document is a main
document
with an attached data source.

Set myMerge = ActiveDocument.MailMerge
If myMerge.State = wdMainAndDataSource Then MyMerge.Execute

#save out result
new_doc.SaveAs(doc_final_name)

#cleanup
doc.Close()
new_doc.Close()
app.Quit()


*I found some information here:
http://64.233.161.104/search?q=cache...document&hl=en

and here:
http://www.brunningonline.net/simon/...es/001299.html

as well as here:
http://www.win32com.de/index.php?opt...=86&Itemid=192

I also have the Hammond and Robinson book on Python on Win32 but it
hasn't helped me to discover the method name.


Sep 30 '05 #2
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()

Oct 5 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Andy | last post by:
I am trying to do the following from an ASP.NET Web Application (C#). User fills out a form. The program takes those answers and merges them with a WORD document. I have tried the few examples...
4
by: Tom Dauria | last post by:
What I am trying to do is write a resume into a word document from information in an Access database. I have been using bookmarks and inserting table results into the document and so far it's...
0
by: dixie | last post by:
I have an application which does a lot of reports (letters) by automation with Word. The mail merge main document is a Word template and I transfer a text file out to a prenamed filename to act as...
1
by: John Davy | last post by:
I am trying to set up a mail merge by automation using a text file as the data source but I keep getting the message "Requested object is not available" and the debugger stops on the...
1
by: Rachel | last post by:
I have just started to rewrite an application using ASP.NET. One of the main features of the application is automated letter production. In the old application this had been accomplished using...
3
by: Bishman | last post by:
Hi, I have some issues with the code below. These are: ONE: In code I open an existing document and 'attach' the Mail Merge data source, but the data is not poulating the merge fields...
12
by: Steve | last post by:
I've been building an application that will merge fields in a text file with a word template, save the resulting word file out to the user's hard drive, and then email the file as an attachment. ...
7
by: =?Utf-8?B?QmFkaXM=?= | last post by:
Hi, I'm trying to follow a mail merging example in C#.Net that I got from: http://support.microsoft.com/default.aspx/kb/301659 and in one the methods: Word.Application wrdApp; Word._Document...
7
by: giladp1 | last post by:
I found Albert Kallal's great "Super easy Word Merge" code in his site at: http://www.members.shaw.ca/AlbertKallal/msaccess/msaccess.html Thanks Albert so much for sharing this. I am looking...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.