Skip to content

Instantly share code, notes, and snippets.

@GastonDonnet
GastonDonnet / python-docx-replace-text-and-retain-style.py
Last active April 11, 2024 16:55 — forked from adejones/python-docx-replace-text-and-retain-style.py
Updated to support multiple replaces of the same KEY in a PARAGRAPH
def docx_replace(doc, data):
paragraphs = list(doc.paragraphs)
for t in doc.tables:
for row in t.rows:
for cell in row.cells:
for paragraph in cell.paragraphs:
paragraphs.append(paragraph)
for p in paragraphs:
for key, val in data.items():
key_name = '${{{}}}'.format(key) # use placeholders in the form ${PlaceholderName}
def docx_replace(doc, data):
paragraphs = list(doc.paragraphs)
for t in doc.tables:
for row in t.rows:
for cell in row.cells:
for paragraph in cell.paragraphs:
paragraphs.append(paragraph)
for p in paragraphs:
for key, val in data.items():
key_name = '${{{}}}'.format(key) # use placeholders in the form ${PlaceholderName}