Replace template text in DOCX files with values from JSON
Project description
docx-json-replacer
A Python library and CLI tool for replacing template placeholders in DOCX files with JSON data, including support for formatted tables with colors and styling.
✨ New in v0.5.0: Table Support!
Create professional Word documents with formatted tables directly from JSON data. Tables support custom colors, backgrounds, bold text, and multiple data formats.
Installation
pip install docx-json-replacer
# or
pip3 install docx-json-replacer
Quick Start
CLI Usage
# Basic text replacement
docx-json-replacer template.docx data.json
# Specify output file
docx-json-replacer template.docx data.json -o output.docx
Python API
from docx_json_replacer import DocxReplacer
# Create replacer instance
replacer = DocxReplacer("template.docx")
# Replace with JSON data (including tables)
replacer.replace_from_json({
"name": "John Doe",
"date": "2025-01-15",
"sales_table": [
{"cells": ["Month", "Revenue"], "style": {"bg": "4472C4", "color": "FFFFFF", "bold": True}},
{"cells": ["January", "$100K"], "style": {"bg": "F2F2F2"}}
]
})
# Save the result
replacer.save("output.docx")
📊 Table Support
1. Styled Tables with Colors
{
"financial_data": [
{
"cells": ["Quarter", "Revenue", "Profit"],
"style": {
"bg": "1F4788", // Background color (hex without #)
"color": "FFFFFF", // Text color
"bold": true, // Bold text
"italic": false // Italic text
}
},
{
"cells": ["Q1 2024", "$2.5M", "$500K"],
"style": {"bg": "E8F4FD"}
},
{
"cells": ["Q2 2024", "$2.8M", "$600K"],
"style": {"bg": "FFFFFF"}
}
]
}
2. Simple List Tables
{
"product_list": [
["Product", "Price", "Stock"],
["Laptop", "$999", "15 units"],
["Mouse", "$29", "50 units"],
["Keyboard", "$79", "32 units"]
]
}
3. Dictionary Tables (Auto-Headers)
Headers are automatically generated from object keys:
{
"employee_data": [
{"name": "Alice Johnson", "department": "Engineering", "salary": 95000},
{"name": "Bob Smith", "department": "Marketing", "salary": 75000},
{"name": "Carol White", "department": "HR", "salary": 65000}
]
}
4. HTML Table Parsing
{
"html_report": "<table><tr><th>Metric</th><th>Value</th></tr><tr><td>Users</td><td>1,250</td></tr><tr><td>Revenue</td><td>$50K</td></tr></table>"
}
Template Format
Use {{key}} placeholders in your DOCX file:
template.docx:
Company Report
Company: {{company}}
Date: {{date}}
Financial Summary:
{{financial_table}}
Products:
{{product_list}}
data.json:
{
"company": "TechCorp International",
"date": "2025-01-15",
"financial_table": [
{"cells": ["Metric", "Q1", "Q2"], "style": {"bg": "4472C4", "color": "FFFFFF", "bold": true}},
{"cells": ["Revenue", "$45M", "$52M"], "style": {"bg": "F2F2F2"}},
{"cells": ["Profit", "$12M", "$15M"], "style": {"bg": "FFFFFF"}}
],
"product_list": [
["Product", "Units Sold"],
["Software", "500"],
["Services", "200"]
]
}
Color Reference
Use hex color codes without the # symbol:
| Color | Hex Code | Usage |
|---|---|---|
| Dark Blue | 1F4788 |
Headers |
| Medium Blue | 4472C4 |
Primary headers |
| Light Blue | E8F4FD |
Alternating rows |
| Green | D4EDDA |
Success/Positive |
| Yellow | FFF3CD |
Warning |
| Red | F8D7DA |
Alert/Negative |
| Light Gray | F2F2F2 |
Alternating rows |
| White | FFFFFF |
Default/Text on dark |
Complete Example
1. Create Template (template.docx)
Annual Business Report
Company: {{company}}
Report Date: {{report_date}}
Prepared by: {{author}}
Executive Summary:
{{summary}}
Department Performance:
{{department_table}}
Risk Assessment:
{{risk_table}}
2. Prepare Data (data.json)
{
"company": "Global Tech Solutions",
"report_date": "2025-01-15",
"author": "Analytics Team",
"summary": "Strong performance across all departments with 23% YoY growth.",
"department_table": [
{
"cells": ["Department", "Budget", "Utilization", "Performance"],
"style": {"bg": "495057", "color": "FFFFFF", "bold": true}
},
{
"cells": ["Engineering", "$2.5M", "94%", "Excellent"],
"style": {"bg": "D4EDDA"}
},
{
"cells": ["Sales", "$1.8M", "88%", "Very Good"],
"style": {"bg": "FFFFFF"}
},
{
"cells": ["Operations", "$1.2M", "78%", "Needs Improvement"],
"style": {"bg": "FFF3CD"}
}
],
"risk_table": [
{
"cells": ["Risk", "Level", "Mitigation"],
"style": {"bg": "DC3545", "color": "FFFFFF", "bold": true}
},
{
"cells": ["Cybersecurity", "High", "24/7 monitoring"],
"style": {"bg": "F8D7DA"}
},
{
"cells": ["Market Competition", "Medium", "Innovation focus"],
"style": {"bg": "FFF3CD"}
}
]
}
3. Generate Report
docx-json-replacer template.docx data.json -o report.docx
Or with Python:
from docx_json_replacer import DocxReplacer
replacer = DocxReplacer("template.docx")
replacer.replace_from_json_file("data.json")
replacer.save("report.docx")
API Reference
DocxReplacer Class
class DocxReplacer:
def __init__(self, docx_path: str)
"""Initialize with template document path"""
def replace_from_json(self, json_data: Dict[str, Any]) -> None
"""Replace placeholders with JSON data"""
def replace_from_json_file(self, json_path: str) -> None
"""Load JSON from file and replace"""
def save(self, output_path: str) -> None
"""Save the modified document"""
Utility Function
replace_docx_template(docx_path: str, json_data: Dict[str, Any], output_path: str) -> None
"""One-line replacement function"""
Local Development
Run Tests
# Run all tests
python -m pytest tests/ -v
# Run specific test
python -m pytest tests/test_table_handler.py -v
Test Table Features
# Create a test document with tables
python test_simple.py
Requirements
- Python 3.7+
- python-docx >= 0.8.11
- docxtpl >= 0.20.0
License
MIT License - See LICENSE file for details
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
Support
For issues, questions, or feature requests:
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file docx_json_replacer-0.5.0.tar.gz.
File metadata
- Download URL: docx_json_replacer-0.5.0.tar.gz
- Upload date:
- Size: 15.4 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.11.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
afececc1ca345b6e5bfbd0e8f2a53d77c05eca0745a40d4fa03fca02bfc3d8b4
|
|
| MD5 |
37c8be34edcd2816a67b066a8bde163a
|
|
| BLAKE2b-256 |
57664012e500945bdd479b229bb71fc7d4f55cb012294b50cfdba0fba7516ae1
|
File details
Details for the file docx_json_replacer-0.5.0-py3-none-any.whl.
File metadata
- Download URL: docx_json_replacer-0.5.0-py3-none-any.whl
- Upload date:
- Size: 14.9 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.11.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
d3659a58c48b3ab3e313362ba1b41ced0dfb81e84feb658a31b9869b2e7ae51e
|
|
| MD5 |
d49907adeb3b9a8acccc3691ee864818
|
|
| BLAKE2b-256 |
3b2919b5249c1962a557e86eca1bb9ce6d838ac08944237b86551310662606a8
|