473,406 Members | 2,867 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,406 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 12458

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: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

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.