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:V-xpWKigqVQJ:coderforums.com/archive/topic/1514-1.html+win32com+merge+to+new+document&hl=en > > and here: > http://www.brunningonline.net/simon/blog/archives/001299.html > > as well as here: > http://www.win32com.de/index.php?option=com_content&task=category§ionid=7&id=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. -- http://mail.python.org/mailman/listinfo/python-list
