Word offers too many choices for building a document: you can loop over a document’s contents, search for elements such as words or paragraphs, and select any portion of the text to work with. We’ll assume you want to build a document in order from beginning to end.
Let’s start with a Python class to help automate the
production of documents. First we’ll construct an object that
has a pointer to a Word document, then add the desired methods one at
a time. The class is called
and can be found in the module
. Here are some of its methods:
class WordWrap: """Wrapper around Word 8 documents to make them easy to build. Has variables for the Applications, Document and Selection; most methods add things at the end of the document""" def __init__(self, templatefile=None): self.wordApp = Dispatch('Word.Application') if templatefile == None: self.wordDoc = self.wordApp.Documents.Add() else: self.wordDoc = self.wordApp.Documents.Add(Template=templatefile) #set up the selection self.wordDoc.Range(0,0).Select() self.wordSel = self.wordApp.Selection #fetch the styles in the document - see below self.getStyleDictionary() def show(self): # convenience when developing self.wordApp.Visible = 1 def saveAs(self, filename): self.wordDoc.SaveAs(filename) def printout(self): self.wordDoc.PrintOut() def selectEnd(self): # ensures insertion point is at the end of the document self.wordSel.Collapse(0) # 0 is the constant wdCollapseEnd; don't want to depend # on makepy ...