python-docx-ml6: Microsoft Word .docx File Manipulation

1.0.2 · active · verified Thu Apr 16

python-docx-ml6 is a Python library for creating, reading, and updating Microsoft Word 2007+ (.docx) files. It is a fork from the original `python-docx` library, specifically including feature requests provided by the open-source community that have not yet been merged into the upstream project. The current version is 1.0.2, released in November 2023, indicating an active development and maintenance cadence.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a new Word document, add headings, paragraphs with formatted text (bold/italic), insert an image, and create a simple table. It then saves the document to a .docx file.

from docx import Document
from docx.shared import Inches

# Create a new document
document = Document()

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

# Add a paragraph
p = document.add_paragraph('A plain paragraph having some ')
p.add_run('bold').bold = True
p.add_run(' and some ')
p.add_run('italic.').italic = True

# Add a heading with level 1
document.add_heading('Heading, level 1', level=1)

# Add a picture
document.add_picture('path/to/image.png', width=Inches(1.25))

# Add a table
records = (
    (3, '101', 'Spam'),
    (7, '422', 'Eggs'),
    (4, '631', 'Spam, eggs, and bacon'),
)

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()

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

view raw JSON →