Sometimes you have to create loads of M$ Word documents, with only small changes in all of them. Given that we’re in the software business, it makes sense to automate this. As Python is a fantastic scripting language, we’lll use it in this article just to do that.
The magic that makes this all happen is the Python Win32 Extensions module from Mark Hammond. This allows you to access COM (aka OLE, ActiveX or whatever the Microsoft marketing machine calls is these days) objects. As Word is a COM object, we can start it and use it to make changes to existing (or new) documents.
In this particular case, a Word document had to be created for a delivery. As most of these documents are the same, with only a defect number changed, a template Word dcument was created. This is then loaded, and the Word search and replace functionality is used to change some placeholder text. Here’s the code :
import win32com.client
fileNm = r'C:\data\template.doc'
word = win32com.client.Dispatch("Word.Application")
word.visible = 1
doc = word.Documents.Open(fileNm)
myrange = doc.Content
myrange.Find.Execute(FindText="xxxx",
ReplaceWith="666", Replace=2, MatchCase=1)
while myrange.Find.Found:
myrange.Text = '666'
myrange = doc.Content
myrange.Find.Execute(FindText="xxxx",
ReplaceWith="666", Replace=2, MatchCase=1)
word.Documents.Item(1).Save()
word.Documents.Item(1).Close()
We first start up Word using the Dispatch method. Then we make it visible by setting the visible property to 1. This is not strictly necessay, but very useful during testing. A file is opened, and we start looking for the placeholder text xxxx. If this is found we change it to be 666. Notice that the range object is set to the found text if the search is successful. We continue the search as long as the placeholder string is found. Lastly we save and close the document.
The hardest part about this is trying to figure out how to use the Word object model exposed through COM. The best way to do this is by looking at the Visual Basic examples on the Microsoft website. These translate easily into Python. Googling also helps.
The Word version used is Word 2002.
Copyright (c) 2024 Michel Hollands