Automating Microsoft Word with Python win32com: Creating and Formatting Documents
This tutorial demonstrates how to use Python's win32com library to control Microsoft Word via its COM object model, covering installation, creating and opening documents, manipulating selections and ranges, and applying page layout and style settings to meet official formatting standards.
This guide explains how to use Python's win32com (pypiwin32) library to control Microsoft Word via its COM object model.
First, install the library with pip install pypiwin32 , then import and create a Word application instance:
from win32com.client import Dispatch
app = Dispatch('Word.Application')Make the Word window visible ( app.Visible = 1 ) and create or open a document ( doc = app.Documents.Add() or doc = app.Documents.Open('path') ).
The Selection object represents the current cursor or selected range. You can obtain it with s = app.Selection , replace its text ( s.Text = 'Hello, world!' ), or insert text with s.TypeText('Hello, world!') . The Range object defines a continuous region independent of the selection.
Key Word objects include Application , Document , Selection , Range , Font , ParagraphFormat , PageSetup , and Styles . Each can be accessed via the COM model, e.g., font = s.Font or pf = s.ParagraphFormat .
To format a document according to national standards, set page margins and layout using doc.PageSetup , adjust the normal style font, and configure line/character grids. Example margin settings (in centimeters converted to points):
cm_to_points = 28.35
doc.PageSetup.TopMargin = 3.3 * cm_to_points
doc.PageSetup.BottomMargin = 3.3 * cm_to_points
doc.PageSetup.LeftMargin = 2.8 * cm_to_points
doc.PageSetup.RightMargin = 2.6 * cm_to_pointsPage numbering can be added via the header/footer selection, setting start number, style, and inserting decorative characters.
The article also suggests using Word's macro recorder and object browser (Alt+F11, F2) to discover methods, and using Python IDLE for interactive testing.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.