Automating Word Document Creation
For simple documents, it is often quicker to create them directly in a word processing program.
But what if you need to:
- Insert data from an Excel file into a Word document, especially when dealing with large datasets?
- Generate recurring reports, such as
monthly sales reports
, using the same document template?
In such cases, automating document creation with Python is a much more efficient solution.
Click the green ▶︎ Run
button in the code editor to generate a table inside a Word document!
Easy-to-Understand Code Explanation
There’s no need to feel overwhelmed by complex-looking code.
By learning Python basics and leveraging AI-assisted coding, you’ll gain a solid understanding of how the code in the practice screen works.
Let AI handle the coding—you just need to understand the concepts.
1. Importing Required Libraries
# Library for handling Excel files
import openpyxl
# Library for creating and editing Word documents
from docx import Document
2. Loading the Excel File
# Load the Excel file containing data
wb = openpyxl.load_workbook('input_file.xlsx')
# Get the currently active sheet
sheet = wb.active
3. Creating a Word Document
# Create a new Word document
doc = Document()
4. Adding a Report Title
# Add a title to the Word document
doc.add_heading('2024 Q1 Sales Performance Report', 0)
5. Creating a Table and Setting Column Headers
# Create a table with 1 row and 5 columns
table = doc.add_table(rows=1, cols=5)
# Add a border style to the table
table.style = 'Table Grid'
# Set the first row (column headers)
hdr_cells = table.rows[0].cells
# Set column headers
hdr_cells[0].text = 'Month'
hdr_cells[1].text = 'Product'
hdr_cells[2].text = 'Quantity Sold'
hdr_cells[3].text = 'Unit Price'
hdr_cells[4].text = 'Revenue'
6. Adding Excel Data and Saving the Word Document
# Read data from the second row and add it to the table
for row in sheet.iter_rows(min_row=2, values_only=True):
# Save each column's data into variables
month, product, sales, price, revenue = row
# Add a new row to the table
row_cells = table.add_row().cells
row_cells[0].text = str(month) # Convert 'Month' data to text and add it
row_cells[1].text = product # Add 'Product' data
row_cells[2].text = str(sales) # Convert 'Quantity Sold' data to text and add it
row_cells[3].text = str(price) # Convert 'Unit Price' data to text and add it
row_cells[4].text = str(revenue) # Convert 'Revenue' data to text and add it
# Save the Word document as 'output_file.docx'
doc.save('output_file.docx')
The process of creating .xlsx
, .pptx
, and .docx
files with Python will be covered more in detail in Chapters 1 and 2 of the Essential Knowledge Course for Automating Tasks to Get Off Work Early.
For now, try running the code and get a feel for what you’ll be learning! 🚀