How to create Word Documents Using Python: A Beginner’s Guide
Python has opened users to a world of automation and document generation opportunities. Small business owners, teachers, and developers are using Python to generate Word documents. Through Python, users can avoid manually personalizing 100 thank-you letters or generating invoices from an Excel sheet. Instead, Python uses just a few lines of code to automatically generate dynamic Word documents that are perfectly formatted.
This blog walks you through a step-by-step process for generating Word documents using Python. Even if you do not have any prior experience with document generation or Python, keep reading to understand how Python-based document generation works!
Key Takeaways
- How to install and use python-docx
- How to generate Word documents using Python
- How to add headings, paragraphs, styles, images, and tables
- How to create multiple dynamic documents
- How to troubleshoot common issues
Let us better understand how Python-based document generation works: If I were to use an analogy to explain the process, it would best be described as a building. Think of creating a Word document programmatically, like constructing a building. You first need a solid foundation (Python environment setup), then come the architectural blueprints (your code structure), followed by quality materials (the python-docx library), and finally, skilled construction techniques (proper implementation methods) to create a perfectly formatted document.
Python is smoother, faster, and error-free. So Python handles the tasks, but maintaining the code itself would become a full-time job. Especially if you’re handling thousands of records, complex templates, or need role-based access and document approval flows. Perfect Doc Studio is designed for individuals, teams, and businesses wanting to automate large-scale documents. It can help you with invoices, contracts, or reports with flexible data inputs from Excel, APIs, or web forms, and offers multichannel delivery.
Perfect Doc Studio is not a replacement for what you will learn in this blog, but the next step up if you ever need it. Click Here to sign up for free!
Why Generate Word Documents Programmatically?
Generating documents programmatically is an efficient and flexible approach in many senses:
- Efficiency that comes with automation: Enhances productivity and saves time.
- Consistency and accuracy it offers: The uniformity in formatting and reduced chances of errors.
- Flexibility to customize: Not just dynamic content but also reusable templates.
- Scalability and adaptability: Capable of handling small and large volumes
- Version control and tracking capabilities: Maintenance of audit trails and consistent and immediate updates across all generated documents.
Some might think it is as simple as automating repetitive tasks, but it is so much more.
Use Cases
- Invoices
- HR documentation (Employment letters, notices, and more)
- Legal documentation
- Reports
Our insights on Dynamic Document Generation informs on business automation that not only includes code-based solutions but also alternatives that go beyond code.
Step 1: Step Up Your Foundation
Installing Required Libraries
We must install python-docx, a library for creating and editing .docx files.
Open your terminal (or Command Prompt) and run:
pip install python-docx
Verify Your Installation
import docx print("python-docx successfully installed!") print(f"Version: {docx.__version__}")
Step 2: Think of a Document Like the Building we Spoke About Earlier
Creating a Word Document is like constructing a building:
➤ The document is your building
➤ Paragraphs are your rooms
➤ Runs (text segments inside paragraphs) are the furniture
➤ Headings are labels on doors
➤ Sections are floors or wings of the building
➤ Styles are paint and decor.
Understanding this helps beginners get the hang of the process and its steps.
Step 3: Your First Word Document in Python (Basic)
Let’s start by creating a basic Word document with a heading and a paragraph.
from docx import Document
# Create a new document (your empty house) doc = Document() # Add a heading (like putting a title on the front door) doc.add_heading("Welcome to Python Word Automation", level=1) # Add a paragraph (a room in the house) doc.add_paragraph("This Word document was generated using Python. Cool, right?") # Save the document doc.save("my_first_doc.docx")
Once you run this script, you will have generated your first automated Word document.
How to Style Text and Add Tables in Python-Docx
Step 4: Let’s Add Styles, Bold Text, and More
Want to change the style of the text? This is where run comes in.
To customize the font (for instance, making it Arial, 14 pt, in blue), you will need to access the run’s font object.
from docx.shared import Pt, RGBColor paragraph = doc.add_paragraph() run = paragraph.add_run("Custom styled text") # Access the font font = run.font font.name = 'Times New Roman' font.size = Pt(14) font.color.rgb = RGBColor(0, 0, 255) # Blue
How to make the text bold, italic, or underlined?
paragraph = doc.add_paragraph() run = paragraph.add_run("This part is bold and italic.") run.bold = True run.italic = True
How to add bullet points or numbered lists?
doc.add_paragraph("First item", style='ListBullet') doc.add_paragraph("Second item", style='ListBullet')
How to add headings for different levels?
doc.add_heading("Main Section", level=1) doc.add_heading("Subsection", level=2)
Step 5: Adding Images
Want to insert your company’s logo, profile picture, or chart?
doc.add_picture("logo.png", width=Inches(2))
Make sure to import:
from docx.shared import Inches
Step 6: Adding Tables
If you’re generating invoices, reports, or structured data, this would be necessary.table doc.add_table(rows=1, cols=3) hdr_cells = table.rows[0].cells hdr_cells[0].text = 'Item' hdr_cells[1].text = 'Quantity' hdr_cells[2].text = 'Price' # Add a data row row_cells = table.add_row().cells row_cells[0].text = 'Apples' row_cells[1].text = '10' row_cells[2].text = '$5'
The Final Step: Generate a Simple Invoice with Python
What it will include: Invoice header, company and customer info, Table of items, total amount, footer message.
from docx import Document from docx.shared import Inches, Pt, RGBColor from docx.enum.text import WD_ALIGN_PARAGRAPH # Create document doc = Document() # Title title = doc.add_heading("INVOICE", level=0) title.alignment = WD_ALIGN_PARAGRAPH.CENTER # Company Info company_info = doc.add_paragraph() company_info.add_run("Your Company Name\n").bold = True company_info.add_run("123 Business St\nCity, State, ZIP\nPhone: (123) 456-7890") # Spacer doc.add_paragraph("\n") # Customer Info doc.add_paragraph("Bill To:", style='Heading2') doc.add_paragraph("John Doe\n456 Client Rd\nClient City, ST 54321") # Spacer doc.add_paragraph("\n") # Table Header table = doc.add_table(rows=1, cols=4) table.style = 'Light Grid' hdr_cells = table.rows[0].cells hdr_cells[0].text = 'Item' hdr_cells[1].text = 'Quantity' hdr_cells[2].text = 'Unit Price' hdr_cells[3].text = 'Total' # Sample data items = [ ("Website Design", 1, 500), ("Hosting (12 months)", 1, 120), ("Domain (1 year)", 1, 15), ] # Add items to table for item, qty, price in items: row_cells = table.add_row().cells row_cells[0].text = item row_cells[1].text = str(qty) row_cells[2].text = f"${price:.2f}" row_cells[3].text = f"${qty * price:.2f}" # Calculate total total = sum(qty * price for item, qty, price in items) # Add total row row_cells = table.add_row().cells row_cells[0].text = '' row_cells[1].text = '' row_cells[2].text = 'Total:' row_cells[3].text = f"${total:.2f}" # Spacer doc.add_paragraph("\n") # Footer message footer = doc.add_paragraph() footer.add_run("Thank you for your business!").italic = True footer.alignment = WD_ALIGN_PARAGRAPH.CENTER # Save the document doc.save("invoice.docx")
Make sure to put the output path for the project in the last line of code.
Output Preview:
For the above code, here is what the output would look like.

How to Generate Multiple Documents Dynamically
If you have a list of names and want to generate personalized letters, you can try this code.
names = ["Alice", "Bob", "Charlie"] for name in names: doc = Document() doc.add_heading("Personalized Letter", level=1) doc.add_paragraph(f"Dear {name},\n\nThank you for learning Python!") doc.save(f"{name}_letter.docx")
This is just like Mail Merge’s automation but in just a few lines of code.
For those looking at generating PDFs using Python, we have a step-by-step tutorial!
Let’s Look at Some Beginner Errors and How to Fix Them
Problem | Cause | Solution |
---|---|---|
FileNotFoundError | Wrong image/file path | Double-check the path or use absolute paths |
docx.opc.exceptions.PackageNotFoundError | Trying to open a .doc (not .docx) file | Only .docx files are supported |
Styles not applying | Misspelled or incorrect style name | Use built-in styles like ‘ListBullet’, ‘Normal’, ‘Heading1’ |
Document not saving | The file opens in Word while saving | Close the .docx file before running the script |
ValueError: binary content expected | Attempting to insert images as a string path incorrectly in templates | When inserting images in docxtpl, use InlineImage and pass the image as a binary |
TemplateError: Missing {{ placeholder }} | Your Word template has a placeholder that doesn’t match your data keys | Double-check spelling and capitalization of placeholders — they must match exactly |
Pro Tip: If you want to debug why placeholders aren’t populating, try printing the context dictionary just before rendering:
print(context) # See what data is being sent to the template
doc.render(context)
“You can also follow along with our video: Create Word Documents from Excel using Python, which visually explains the steps covered here.”
So, now that you’ve looked at the basics, what comes next? As beginners, users should expand their skills, start small, learn to use conditional logic, and try pulling data from Excel using openpyxl.
If you are interested in learning how to generate bulk Word documents from Excel using Python, click here to read our comprehensive guide.
Automating Word documents with Python might sound like a herculean task for a beginner. However, once you see Python’s possibilities, it will quickly become your go-to for document generation needs. With the ability to combine templates, data sources, and dynamic content, you can stop relying on copy-paste.
Whatever you’ve learned, experiment with it to start replacing repetitive tasks. Intelligent automation can take you places with just a few lines of code.
FAQs
Python uses libraries like python-docx, Openpyxl and others to let you create, style, format, and populate Word documents through code. Some examples of what Python can help you create are invoices, personalized letters, or reports from data in Excel or databases.
Not at all! You only need to have basic Python knowledge to use python-docx. This is a library that is designed to be user-friendly, in the sense that many tasks like adding headings, paragraphs, or tables require only a few lines of code. If you’re just starting out, you can always refer to a multitude of tutorials available on YouTube.
Yes, there are Python libraries like Openpyxl and pandas that read Excel files. Another Python library like Python-docx can be used to create Word documents from that data. This is method is similar to Mail Merge but offers more flexibility.
Absolutely! The python-docx library supports adding images, creating tables, and applying built-in font styles, colors, and formatting. Additionally, you can also opt for custom font styles to ensure consistent branding.
Python offers flexibility and control, but it it is ideal only for developers, custom integrations, or those with Python knowledge. On the other hand, non-technical users need no-code platforms like Perfect Doc Studio, it offers large scale deployments, role-based access, increased compliance, and much more.
Yes! Python supports PDF generation with libraries like reportlab or pdfkit, and you can even combine Word and PDF workflows—for example, generating a Word document first, then converting it to PDF. For more details, see our guide on generating PDFs with Python.
How to Generate PDF documents Using Python?
In this blog, we will guide you through a comprehensive, step-by-step process for generating PDF doc
What is PHP PDF Generator? How to Generate PDFs with Php: A step-by-step guide
One of the reasons you might enjoy PHP so much is because it consistently supports new technologies.
PDF QR Code Generator : How To Create QR Code For PDF?
Have you wondered how the QR codes automatically link you to PDFs when scanned? In today’s fas