I recently needed to automate dividend slip generation through a Python solution. The project required reading shareholder data from CSV, locating a Word template, substituting placeholder text with specific details, and saving customized documents without altering the original.

The Challenge

I needed to accomplish five key tasks:

  1. Extract amounts, dates, and addresses from a CSV file
  2. Verify that output files didn’t already exist
  3. Load a Word document template
  4. Replace placeholder “trigger words” with actual data
  5. Save generated documents separately from the template

Solution Approach

Rather than relying on built-in find-and-replace functionality, I leveraged python-docx to iterate through document paragraphs and apply Python’s string replacement methods to swap placeholder values for actual data.

Implementation

import docx
import csv
import pathlib

if __name__ == "__main__":
    with open("Dividends.csv") as f:
        reader = csv.DictReader(f)
        for line in reader:
            print("Checking: " + line["Date"] + ".docx")
            if pathlib.Path(line["Date"] + ".docx").exists() == False:
                doc = docx.Document("dividend-template.docx")
                if line["Amount"] != "":
                    print("Generating new Dividend slip for: " + line["Date"])
                    for paragraph in doc.paragraphs:
                        if "DTE" in paragraph.text:
                            orig_text = paragraph.text
                            new_text = str.replace(orig_text, "DTE", line["Date"])
                            paragraph.text = new_text
                        if "AMNT" in paragraph.text:
                            orig_text = paragraph.text
                            new_text = str.replace(orig_text, "AMNT", line["Amount"])
                            paragraph.text = new_text
                        if "ADDR" in paragraph.text:
                            orig_text = paragraph.text
                            new_text = str.replace(orig_text, "ADDR", line["Address"])
                            paragraph.text = new_text
                    print("Saving: " + line["Date"] + ".docx")
                    doc.save(line["Date"] + ".docx")

The key insight is that python-docx gives you access to paragraph objects, which you can then manipulate using standard Python string methods. This approach is more flexible than Word’s native find-and-replace when you need programmatic control over the substitution logic.