python-docx

1.2.0 · active · verified Sat Mar 28

python-docx is a Python library for creating, reading, and updating Microsoft Word (.docx) files. It allows programmatic manipulation of Word documents without requiring Microsoft Word or similar software to be installed. The current version is 1.2.0, and the project is actively maintained.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a new Word document, add a top-level heading, a paragraph with styled text (bold and italic), and a basic table with a predefined style, then save it to a .docx file.

from docx import Document

# Create a new document
document = Document()

# Add a heading
document.add_heading('My Awesome Document', level=0)

# Add a paragraph
p = document.add_paragraph('This is a simple paragraph with some ')
p.add_run('bold text').bold = True
p.add_run(' and some ')
p.add_run('italic text').italic = True

# Add a table
table = document.add_table(rows=1, cols=3)
table.style = 'Light Shading Accent 1'
heading_cells = table.rows[0].cells
heading_cells[0].text = 'Qty'
heading_cells[1].text = 'Item'
heading_cells[2].text = 'Price'

# Add more rows to the table
row_cells = table.add_row().cells
row_cells[0].text = '1'
row_cells[1].text = 'Widget A'
row_cells[2].text = '$10.00'

# Save the document
document.save('my_example.docx')
print("Document 'my_example.docx' created successfully.")

view raw JSON →