Fundamentals 9 min read

Automate Excel-to-Word Reporting with Python: A Step‑by‑Step Guide

This article walks through using Python to read and process data from an Excel file, generate a structured filename, convert legacy .doc files to .docx, and automatically populate a Word document’s tables, providing a complete automation workflow for reporting tasks.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
Automate Excel-to-Word Reporting with Python: A Step‑by‑Step Guide

Introduction

In a previous article we showed how to extract data from Word tables to Excel. This article demonstrates how to use Python to read data from an Excel file, process it, and automatically fill a Word document according to specific rules.

Requirements

The Excel data contains many rows, duplicates, and must be transformed and written into a Word file. The output Word filename must also follow a naming convention.

Python implementation – Excel parsing

from openpyxl import load_workbook
import os
# 获取桌面的路径
def GetDesktopPath():
    return os.path.join(os.path.expanduser("~"), 'Desktop')

path = GetDesktopPath() + '/资料/'  # 形成文件夹的路径便后续重复使用
workbook = load_workbook(filename=path + '数据.xlsx')
sheet = workbook.active  # 获取当前页
# 可以用代码获取数据范围,如果要批处理循环迭代也方便
# 获取有数据范围
print(sheet.dimensions)  # A1:W10

Using openpyxl we read cells, deduplicate values, format strings, compute totals, and build a descriptive filename.

Converting .doc to .docx (Windows)

# pip install pypiwin32
from win32com import client

def doc2docx(doc_path, docx_path):
    word = client.Dispatch("Word.Application")
    doc = word.Documents.Open(doc_path)
    doc.SaveAs(docx_path, 16)
    doc.Close()
    word.Quit()
    print('
 doc文件已转换为docx 
')

if not os.path.exists(docx_path):
    doc2docx(doc_path, docx_path)

This converts legacy .doc templates to .docx so they can be processed with python-docx.

Word filling

from docx import Document

document = Document(docx_path)
tables = document.tables
# Example of writing values
tables[0].cell(1, 1).text = SQE
tables[1].cell(1, 1).text = supplier
tables[1].cell(2, 1).text = supplier
tables[1].cell(3, 1).text = ptype
tables[1].cell(4, 1).text = info
tables[1].cell(5, 1).text = order_num
tables[1].cell(7, 1).text = time

All data must be converted to strings before writing, and table indices start at 0.

Filling a detailed table

for i in range(2, 11):
    tables[6].cell(i, 0).text = str(sheet[f'T{i}'].value)
    tables[6].cell(i, 1).text = str(sheet[f'P{i}'].value)
    tables[6].cell(i, 2).text = str(sheet[f'C{i}'].value)
    tables[6].cell(i, 4).text = str(sheet[f'V{i}'].value)
    tables[6].cell(i, 5).text = str(sheet[f'V{i}'].value)
    tables[6].cell(i, 6).text = '0'
    tables[6].cell(i, 7).text = str(sheet[f'W{i}'].value)
    tables[6].cell(i, 8).text = '0'

tables[6].cell(12, 4).text = str(total_num)
tables[6].cell(12, 5).text = str(total_num)
tables[6].cell(12, 7).text = str(box_num)

Note that merged cells or custom layouts may require index adjustments.

Saving the document

document.save(path + f'{title}.docx')
print('
文件已生成')

Key details

Convert all extracted values to strings before writing to Word.

Table structures may include merged cells; verify indices during development.

Conclusion

After populating all required tables and saving the document, the automated report is generated. Consider whether the task is repetitive enough to justify automation with Python, as manual effort may be sufficient for one‑off cases.

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.

openpyxlpython-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.