Operations 9 min read

Automate Contract Generation with Python, Excel, and Word

This tutorial shows how to use Python's openpyxl and python-docx libraries to read company data from an Excel sheet, replace placeholder tags in a Word contract template, and automatically generate individualized contracts for each company in a batch process.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
Automate Contract Generation with Python, Excel, and Word

Introduction

Hello everyone, welcome back to the Python office automation series. In this article we demonstrate a real automation scenario: using Python+Excel+Word to batch‑generate contracts in a specified format. The key technologies are the openpyxl module for Excel handling and the python-docx library for Word traversal.

Requirement Description

You have a blank Word contract template and an Excel spreadsheet that contains the information of each client (one row per company). The goal is to fill the template with the data from each row and produce a separate contract for every company.

Step Analysis

First, replace the underlines in the Word template with unique placeholders that match the column names in the Excel sheet, e.g., #ColumnName#. The program then searches for these placeholders and substitutes them with the actual cell values.

Analysis steps: Convert the blank contract into a template by changing each underline to a column‑name placeholder. Open the Excel file, iterate over rows, and for each cell find the corresponding placeholder in the template and replace it. After processing all cells of a row, save the modified document as a separate contract for that company.

Code Implementation

Import the required modules, set up paths, and create an output folder.

from docx import Document
from openpyxl import load_workbook
import os

path = r'C:\Users\chenx\Desktop\合同'
if not os.path.exists(path + '/' + '全部合同'):
    os.mkdir(path + '/' + '全部合同')

Load the Excel workbook.

workbook = load_workbook(path + '/' + '合同信息表.xlsx')
sheet = workbook.active

Iterate through each data row, open the Word template, replace placeholders in both paragraphs and tables, and save the result.

# Effective data rows start from the second row (first row is header)
for table_row in range(2, sheet.max_row + 1):
    wordfile = Document(path + '/' + '合同模板.docx')
    for table_col in range(1, sheet.max_column + 1):
        old_text = str(sheet.cell(row=1, column=table_col).value)
        new_text = str(sheet.cell(row=table_row, column=table_col).value)
        if ' ' in new_text:
            new_text = new_text.split()[0]
        # Replace in paragraphs
        for paragraph in wordfile.paragraphs:
            for run in paragraph.runs:
                run.text = run.text.replace(old_text, new_text)
        # Replace in tables
        for table in wordfile.tables:
            for row in table.rows:
                for cell in row.cells:
                    cell.text = cell.text.replace(old_text, new_text)
    company = str(sheet.cell(row=table_row, column=1).value)
    wordfile.save(path + '/' + f'全部合同/{company}合同.docx')

Conclusion

This practical case shows how to automate the repetitive task of filling contracts, and the approach can be extended to any scenario where a structured data source (Excel) needs to populate a document template (Word). Before writing automation scripts, always break the task into clear steps.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonAutomationExcelWordopenpyxlpython-docx
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.