Replace Text within a Word document using IronPython

Software Engineering 2473 views

Below, the doc_replace_text method demonstrates how to replace text within a Word document. This is commonly used as a way to create dynamic, data-driven letters based on a template. The method accepts the name of the template Word document (source_filename), the tokens to look for, the values to replace tokens with, and the destination filename.

Using COM Interop, the template Word document (source_filename) is opened, and the StoryRanges are looped through, replacing found tokens with their corresponding values. The result is then saved as the destination_filename.

import sys
import clr
import System
from System import DateTime

clr.AddReference("Microsoft.Office.Interop.Word")
import Microsoft.Office.Interop.Word as Word

def doc_replace_text(source_filename, tokens, values, destination_filename):

    missing = System.Type.Missing
    replaceAll = Word.WdReplace.wdReplaceAll

    word_application = Word.ApplicationClass()
    word_application.visible = False

    document = word_application.Documents.Open(source_filename)

    for i in range(len(tokens)):
        for r in document.StoryRanges:
            #print "i = %d, tokens[i] = %s, values[i] = %s" % (i, tokens[i], values[i])
            r.Find.Text = tokens[i]
            r.Find.Replacement.Text = values[i]
            r.Find.Wrap = Word.WdFindWrap.wdFindContinue
            r.Find.Execute(missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, replaceAll, missing, missing, missing, missing)

    document.SaveAs(destination_filename)
    document.Close()
    document = None

    word_application.Quit()
    word_application = None

Usage could look something like this:

source_filename = "C:\\template.doc"
destination_filename = "C:\\letter.doc"

tokens = ["[Today]", "[First Name]", "[Last Name]", "[Company Name]", "[Address1]"] # etc...
values = [DateTime.Now, client.first_name, client.last_name, client.company_name, client.address1]

doc_replace_text(source_filename, tokens, values, destination_filename)