Creating Word Documents with python-docx
Basics
docx_create.py
from docx import Document
doc = Document()
doc.add_heading("Weekly Report", level=1)
doc.add_paragraph("This report was generated automatically.")
table = doc.add_table(rows=1, cols=2)
hdr = table.rows[0].cells
hdr[0].text = "Item"
hdr[1].text = "Value"
for item, value in [("Users", "120"), ("Errors", "3")]:
row_cells = table.add_row().cells
row_cells[0].text = item
row_cells[1].text = value
doc.save("report.docx")docx_create.py
from docx import Document
doc = Document()
doc.add_heading("Weekly Report", level=1)
doc.add_paragraph("This report was generated automatically.")
table = doc.add_table(rows=1, cols=2)
hdr = table.rows[0].cells
hdr[0].text = "Item"
hdr[1].text = "Value"
for item, value in [("Users", "120"), ("Errors", "3")]:
row_cells = table.add_row().cells
row_cells[0].text = item
row_cells[1].text = value
doc.save("report.docx")Tips
- start from a template .docx for complex formatting
- docx is not the same as PDF (convert separately if needed)
If this helped you, consider buying me a coffee ☕
Buy me a coffeeWas this page helpful?
Let us know how we did
