function add_table_to_word
Adds a formatted table to a Word document using python-docx, with support for header rows and automatic column sizing based on table data.
/tf/active/vicechatdev/vice_ai/new_app.py
4077 - 4124
moderate
Purpose
This function creates and inserts a table into a Word document with proper formatting. It processes table data structured as rows with cell content, automatically determines the maximum number of columns needed, applies 'Table Grid' styling, and formats header rows with bold text. The function includes comprehensive logging for debugging and adds spacing after the table for document readability.
Source Code
def add_table_to_word(doc, table_data):
"""Add a table to Word document with proper formatting"""
if not table_data:
logger.info("No table data provided")
return
logger.info(f"Processing table with {len(table_data)} rows")
for i, row in enumerate(table_data):
logger.info(f"Row {i}: type={row.get('type')}, cells={row.get('cells')}")
# Count maximum columns
max_cols = max(len(row['cells']) for row in table_data) if table_data else 0
if max_cols == 0:
logger.info("No columns found in table data")
return
logger.info(f"Creating table with {len(table_data)} rows and {max_cols} columns")
# Create table
table = doc.add_table(rows=len(table_data), cols=max_cols)
table.style = 'Table Grid'
for row_idx, row_data in enumerate(table_data):
table_row = table.rows[row_idx]
for col_idx, cell_content in enumerate(row_data['cells']):
if col_idx < max_cols:
cell = table_row.cells[col_idx]
logger.info(f"Setting cell [{row_idx}][{col_idx}] = '{cell_content}'")
# Use the simple text assignment method
cell.text = str(cell_content).strip()
# Style header row
if row_data['type'] == 'header':
# Make first paragraph bold
if cell.paragraphs:
for run in cell.paragraphs[0].runs:
run.bold = True
# If no runs exist, add one
if not cell.paragraphs[0].runs:
run = cell.paragraphs[0].add_run(str(cell_content).strip())
run.bold = True
logger.info("Table creation completed")
# Add spacing after table
doc.add_paragraph()
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
doc |
- | - | positional_or_keyword |
table_data |
- | - | positional_or_keyword |
Parameter Details
doc: A python-docx Document object representing the Word document to which the table will be added. This should be an instance of docx.Document or DocxDocument.
table_data: A list of dictionaries where each dictionary represents a row. Each row dictionary must contain: 'type' (string, e.g., 'header' or 'data') and 'cells' (list of cell content values). Example: [{'type': 'header', 'cells': ['Col1', 'Col2']}, {'type': 'data', 'cells': ['Value1', 'Value2']}]. Can be None or empty list, in which case the function returns early without creating a table.
Return Value
Returns None. The function modifies the provided Document object in-place by adding a table and a paragraph for spacing. If table_data is empty or None, or if no columns are found, the function returns early without making changes.
Dependencies
python-docxlogging
Required Imports
from docx import Document
import logging
Usage Example
from docx import Document
import logging
# Setup logger
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
# Create a new Word document
doc = Document()
# Prepare table data
table_data = [
{'type': 'header', 'cells': ['Name', 'Age', 'City']},
{'type': 'data', 'cells': ['John Doe', '30', 'New York']},
{'type': 'data', 'cells': ['Jane Smith', '25', 'Los Angeles']}
]
# Add table to document
add_table_to_word(doc, table_data)
# Save the document
doc.save('output_with_table.docx')
Best Practices
- Ensure the 'logger' object is properly configured before calling this function to capture debug information
- Validate table_data structure before passing to the function - each row should have 'type' and 'cells' keys
- All rows should ideally have the same number of cells for proper table formatting, though the function handles variable column counts
- Cell content will be converted to strings and stripped of whitespace automatically
- Header rows are identified by 'type': 'header' and will be formatted with bold text
- The function adds a blank paragraph after the table for spacing - consider this when adding subsequent content
- The 'Table Grid' style is applied by default - ensure this style exists in your document template or modify as needed
- For large tables, consider memory implications as the entire table is created at once
- The function returns early if table_data is None, empty, or contains no columns - handle these cases in calling code if needed
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function add_table_to_word_v1 97.3% similar
-
function add_formatted_content_to_word 71.7% similar
-
function add_table_to_pdf_v1 70.3% similar
-
function add_table_to_pdf 68.6% similar
-
function add_formatted_content_to_word_v1 66.4% similar