Skip to content

Checking your reading list…

Retry

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

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_points

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

About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

Pythonscriptingwin32comWord AutomationCOMdocument formatting

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion