Create Word Documents with Python Code
Working on documents is an essential part of many tasks, but manually creating repetitive documents can be very tedious.
For example, if you need to read data from Excel to create reports or populate a Word template with repetitive data to generate multiple pages of documents, doing this manually is highly inefficient.
With python-docx, you can automate these repetitive tasks to save time and effort.
Instead of manually creating 100 documents, you can use python-docx
to generate all the documents with just a few lines of code.
Note: To actually run the sample code on your computer, install the python-docx library with the command
pip install python-docx
.
Creating a Simple Document
Here's a code example to create a simple Word document using python-docx
.
# Import the python-docx library
from docx import Document
# Create a new document
doc = Document()
# Add a heading with level=1 to the document
doc.add_heading('Hello, World!', level=1)
# Add a heading with level=2 to the document
doc.add_heading('This is a sub-heading.', level=2)
# Add a paragraph to the document
doc.add_paragraph("This is a paragraph.")
# Save the document
doc.save('output_file.docx')
When using the python-docx
library, import the necessary classes or functions using from docx import {class or function}
.
First, call Document()
to create a new document. Then, you can add a heading to the document using the add_heading()
method with the specified level
.
The level in the add_heading method can be set from 1 to 9.
level=1
is the largest heading, and as the level number increases to level=9
, the heading becomes smaller.
These heading levels are useful for representing the structure and hierarchy of the document.
To add a paragraph, use the add_paragraph()
method. The created document can be saved with the code doc.save('file_name')
.
The above code creates a new Word document, adds the content "Hello, World!" and "This is a sub-heading.", and saves it as output_file.docx
.
While creating a document like this manually might be quicker, python-docx shows its true potential when integrated with large datasets.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.