Using python-docx to Create and Manipulate Word Documents in Python
This article introduces the python-docx library, explains how to install it, and provides a comprehensive code example that demonstrates creating Word documents, adding headings, formatted text, images, tables, and saving the file, along with links to official documentation and GitHub resources.
Python-Docx is a Python library for creating and updating Microsoft Word (.docx) files, making document automation straightforward.
Installation can be performed with pip: pip install python-docx or, if both Python 2 and 3 are present, with pip3 install python-docx .
The article walks through a complete usage demonstration, starting with importing the library, creating a new document, adding a title heading, paragraphs, bold and italic text, additional headings, bullet and numbered lists, inserting an image, constructing a table with data, adding a page break, and finally saving the document as demo.docx .
# 1. Import python-docx library
from docx import Document
from docx.shared import Inches
document = Document()
document.add_heading('Document Title', 0)
# 2. Add a plain paragraph
p = document.add_paragraph('A plain paragraph having some ')
# 3. Set font formatting
p.add_run('bold').bold = True
p.add_run(' and some ')
p.add_run('italic.').italic = True
document.add_heading('Heading, level 1', level=1)
document.add_paragraph('Intense quote', style='Intense Quote')
document.add_paragraph('first item in unordered list', style='List Bullet')
document.add_paragraph('first item in ordered list', style='List Number')
# 4. Insert an image
document.add_picture('monty-truth.png', width=Inches(1.25))
# 5. Add a table
records = (
(3, '101', 'Spam'),
(7, '422', 'Eggs'),
(4, '631', 'Spam, spam, eggs, and spam')
)
table = document.add_table(rows=1, cols=3)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Qty'
hdr_cells[1].text = 'Id'
hdr_cells[2].text = 'Desc'
for qty, id, desc in records:
row_cells = table.add_row().cells
row_cells[0].text = str(qty)
row_cells[1].text = id
row_cells[2].text = desc
document.add_page_break()
# 6. Save the document
document.save('demo.docx')Additional resources include the official python-docx documentation, which details all features and the full API reference, as well as the project's GitHub page for more examples.
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.