function add_table_to_word_v1
Adds a formatted table to a Microsoft Word document using the python-docx library, with automatic column detection, header row styling, and debug logging.
/tf/active/vicechatdev/vice_ai/complex_app.py
1529 - 1576
moderate
Purpose
This function creates and inserts a table into a Word document object with proper formatting. It processes table data structured as rows with cell content, automatically determines the maximum number of columns, applies grid styling, and bolds header rows. The function includes extensive debug logging to track table creation progress and handles edge cases like empty data or missing columns.
Source Code
def add_table_to_word(doc, table_data):
"""Add a table to Word document with proper formatting"""
if not table_data:
print("DEBUG: No table data provided")
return
print(f"DEBUG: Processing table with {len(table_data)} rows")
for i, row in enumerate(table_data):
print(f"DEBUG: 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:
print("DEBUG: No columns found in table data")
return
print(f"DEBUG: 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]
print(f"DEBUG: 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
print("DEBUG: 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 that has been created or opened prior to calling this function.
table_data: A list of dictionaries where each dictionary represents a table row. Each row dictionary must contain: 'type' (string, typically 'header' or 'data' to indicate row type) and 'cells' (list of strings/values representing cell content). Example: [{'type': 'header', 'cells': ['Col1', 'Col2']}, {'type': 'data', 'cells': ['Val1', 'Val2']}]. Can be None or empty list, in which case the function returns early without creating a table.
Return Value
This function returns None (implicit). It modifies the provided Document object in-place by adding a table and a paragraph spacer. The function performs side effects rather than returning a value.
Dependencies
python-docx
Required Imports
from docx import Document
Usage Example
from docx import Document
# Create a new Word document
doc = Document()
# Prepare table data
table_data = [
{'type': 'header', 'cells': ['Name', 'Age', 'City']},
{'type': 'data', 'cells': ['Alice', '30', 'New York']},
{'type': 'data', 'cells': ['Bob', '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 table_data is properly structured with 'type' and 'cells' keys in each row dictionary before calling
- The function adds debug print statements which should be replaced with proper logging in production environments
- All rows should ideally have the same number of cells to avoid empty cells, though the function handles variable column counts
- Header rows should be marked with 'type': 'header' to receive bold formatting
- The function automatically adds a paragraph spacer after the table for better document formatting
- Cell content is converted to strings and stripped of whitespace automatically
- The 'Table Grid' style is applied by default; modify the table.style line if different styling is needed
- Consider validating table_data structure before passing to this function to avoid runtime errors
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function add_table_to_word 97.3% similar
-
function add_formatted_content_to_word 71.4% similar
-
function add_table_to_pdf_v1 68.6% similar
-
function add_formatted_content_to_word_v1 67.1% similar
-
function add_table_to_pdf 67.1% similar