Mastering Tables in Word with Python: Data, Images, and Styling
Let’s face it: manually building complex tables in Microsoft Word is a time-consuming task, especially when you’re dealing with massive datasets or dozens of images. Whether you're generating automated monthly reports or dynamic invoices, Python is your secret weapon for turning busy work into a streamlined script.
In this guide, we’ll explore how to programmatically construct Word tables, populate them with text and images, and apply professional styling to make your documents pop.
The Tool of the Choice: Spire.Doc for Python
To handle the heavy lifting, we'll be using Spire.Doc for Python. While there are several libraries out there, Spire.Doc stands out because it provides a high-level API that handles complex Word structures—like nested tables and high-resolution image insertion—with minimal code. It essentially gives you Word-level control without ever needing to open the Word application itself.
Installation
Getting started is simple. Just fire up your terminal and run:
pip install Spire.Doc
Example 1: Creating a Basic Table and Populating Data
To get started, let’s look at how to build a table from scratch. The following script initializes a document, defines a data structure for your products, and loops through it to generate rows. We've also included some logic to apply alternating row colors and header styling to ensure your data is as readable as it is accurate.
import math
from spire.doc import *
from spire.doc.common import *
# Create a Document object
doc = Document()
# Add a section
section = doc.AddSection()
# Create a table
table = section.AddTable()
# Specify table data (Updated to English)
header_data = ["Product Name", "Unit", "Quantity", "Unit Price"]
row_data = [ ["Base Plate-1", "pcs", "20946", "2.9"],
["Position Board-2", "sheets", "38931", "1.5"],
["Leveling Mold-3", "sets", "32478", "1.1"],
["Rear Shell FD1042-4", "sets", "21162", "0.6"],
["Roller-5", "sets", "66517", "1.2"]]
# Set the number of rows and columns
table.ResetCells(len(row_data) + 1, len(header_data))
# Auto-fit table to window width
table.AutoFit(AutoFitBehaviorType.AutoFitToWindow)
# Set the header row
headerRow = table.Rows[0]
headerRow.IsHeader = True
headerRow.Height = 23
headerRow.RowFormat.BackColor = Color.get_Orange()
# Fill data in header row and set text formatting
i = 0
while i < len(header_data):
headerRow.Cells[i].CellFormat.VerticalAlignment = VerticalAlignment.Middle
paragraph = headerRow.Cells[i].AddParagraph()
paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center
txtRange = paragraph.AppendText(header_data[i])
txtRange.CharacterFormat.Bold = True
txtRange.CharacterFormat.FontSize = 12
i += 1
# Fill data in the remaining rows and set text formatting
r = 0
while r < len(row_data):
dataRow = table.Rows[r + 1]
dataRow.Height = 20
dataRow.HeightType = TableRowHeightType.Exactly
c = 0
while c < len(row_data[r]):
dataRow.Cells[c].CellFormat.VerticalAlignment = VerticalAlignment.Middle
paragraph = dataRow.Cells[c].AddParagraph()
paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center
txtRange = paragraph.AppendText(row_data[r][c])
txtRange.CharacterFormat.FontSize = 11
c += 1
r += 1
# Set alternating row colors
for j in range(1, table.Rows.Count):
if math.fmod(j, 2) == 0:
row2 = table.Rows[j]
for f in range(row2.Cells.Count):
row2.Cells[f].CellFormat.BackColor = Color.get_LightGray()
# Save the file
doc.SaveToFile("WordTable.docx", FileFormat.Docx2016)
Example 2: Inserting Images into Table Cells
Data is more than just text. Sometimes, you need to include product photos, logos, or icons to make your document informative. In this example, we’ll take an existing document and target specific cells to insert images. Spire.Doc makes this straightforward by allowing you to append a picture directly to a cell's paragraph and then define its exact dimensions for a perfect fit.
from spire.doc import *
from spire.doc.common import *
inputFile = "TableExample.docx"
outputFile = "InsertImageToTable.docx"
# Create a Document object
doc = Document()
# Load the Word document
doc.LoadFromFile(inputFile)
# Get the first table in the document
table = doc.Sections[0].Tables[0]
# Add an image to a specific cell and set the image size
cell = table.Rows[1].Cells[1]
picture = cell.Paragraphs[0].AppendPicture("python.png")
picture.Width = 80
picture.Height = 80
# Add another image to a different cell and set the image size
cell = table.Rows[2].Cells[1]
picture = cell.Paragraphs[0].AppendPicture("java.jpg")
picture.Width = 80
picture.Height = 80
# Save the result file
doc.SaveToFile(outputFile, FileFormat.Docx)
doc.Close()
As you can see from the code above, to insert an image into a Word table, you first need to access the specific cell and then use the TableCell.Paragraphs[index].AppendPicture() method to embed the image.
Wrapping Up
Automating Word tables with Python not only saves hours of manual formatting but also ensures your reports remain consistent and error-free. By mastering data injection and image placement, you can transform raw scripts into professional documents in seconds.
If your workflow involves heavy data crunching before document generation, you might also find Spire.XLS helpful for managing complex Excel datasets seamlessly. Whether you're handling docs or spreadsheets, the right tools make all the difference.