You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
34 lines
1.5 KiB
34 lines
1.5 KiB
from docx import Document
|
|
from docx.shared import Inches
|
|
|
|
def replace(template ,filename, data):
|
|
doc = Document(template)
|
|
# 段落替换
|
|
for paragraph in doc.paragraphs:
|
|
for datum in data:
|
|
if datum["key"] in paragraph.text:
|
|
if "text" == datum["type"]:
|
|
paragraph.text = paragraph.text.replace(datum["key"], datum["value"])
|
|
elif "picture" == datum["type"]:
|
|
paragraph.clear()
|
|
paragraph.add_run().add_picture(datum["value"], width=Inches(datum["width"]))
|
|
elif "number" == datum["type"]:
|
|
paragraph.text = paragraph.text.replace(datum["key"], str(datum["value"]))
|
|
|
|
# 表格替换
|
|
for table in doc.tables:
|
|
for row in table.rows:
|
|
for cell in row.cells:
|
|
for datum in data:
|
|
if datum["key"] in cell.text:
|
|
if "text" == datum["type"]:
|
|
cell.text = cell.text.replace(datum["key"], datum["value"])
|
|
elif "picture" == datum["type"]:
|
|
paragraph = cell.paragraphs[0]
|
|
paragraph.clear()
|
|
paragraph.add_run().add_picture(datum["value"], width=Inches(datum["width"]))
|
|
elif "number" == datum["type"]:
|
|
cell.text = cell.text.replace(datum["key"], str(datum["value"]))
|
|
doc.save(filename)
|
|
|