from docx import Document
from docx.shared import Inches
document = Document()
document.add_heading('Document Title', 0)
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
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'
)
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()
document.save('demo.docx')
print(f"Saved demo.docx with {len(document.paragraphs)} paragraphs and a {len(table.rows)}-row table")python-docx creates and edits Word .docx files from Python. It can add headings, paragraphs, bold and italic text, lists, tables, pictures and page breaks, and it can open an existing document to read or change it. Word does not need to be installed, which is why it is the common choice for generating letters, reports and invoices from data. This page is an online python-docx compiler: the code runs in your browser, so you can try it without installing anything. Run the example first, then paste any snippet below into a new cell to try it.
Document() starts from python-docx's built-in template.
add_heading(text, 0) adds the title, and levels 1 to 9 add headings.
add_paragraph() returns the new paragraph, and each add_run() appends a
piece of text with its own formatting, which is how one sentence mixes
plain, bold and italic words. Styles such as "Intense Quote", "List Bullet"
and "List Number" come from the template. The table starts with one header
row, and add_row() adds a row per record. document.save("demo.docx")
writes the file.
Any image can go in, including a chart drawn with matplotlib:
import matplotlib.pyplot as plt
from docx import Document
from docx.shared import Inches
plt.bar(["Q1", "Q2", "Q3"], [120, 135, 150])
plt.savefig("chart.png", dpi=150)
document = Document()
document.add_heading("Quarterly sales", 1)
document.add_picture("chart.png", width=Inches(5))
document.save("report.docx")
A table has no borders until you give it a style. The built-in template includes Word's table styles:
from docx import Document
document = Document()
table = document.add_table(rows=1, cols=2)
table.style = "Light Grid Accent 1"
table.rows[0].cells[0].text = "Quarter"
table.rows[0].cells[1].text = "Sales"
for quarter, sales in [("Q1", 120), ("Q2", 135)]:
cells = table.add_row().cells
cells[0].text = quarter
cells[1].text = str(sales)
document.save("table.docx")
Document() also opens a file. This prints each paragraph of the file the
example saved, with its style, and then the table:
from docx import Document
document = Document("demo.docx")
for paragraph in document.paragraphs:
if paragraph.text:
print(f"{paragraph.style.name}: {paragraph.text}")
for row in document.tables[0].rows:
print([cell.text for cell in row.cells])
To work on your own document, click Mount folder in the sidebar's Data tab (Chrome or Edge on a computer), choose the folder it is in, and open it by name. Add files takes only CSV, Excel, SQLite and text files.
from docx import Document
from docx.enum.section import WD_ORIENT
from docx.shared import Inches
document = Document()
section = document.sections[0]
section.orientation = WD_ORIENT.LANDSCAPE
section.page_width, section.page_height = section.page_height, section.page_width
section.left_margin = section.right_margin = Inches(0.75)
section.header.paragraphs[0].text = "Quarterly report"
document.save("landscape.docx")
Files your code saves, like demo.docx, appear in the sidebar's Data
tab. Running code and inspecting the result is free. Downloading the
files requires a Premium plan.
text rather than
the paragraph's.