from docx import Document
def generate_document(template_path, data):
# 打开模板文档
template = Document(template_path)
# 遍历模板中的全部段落
for paragraph in template.paragraphs:
# 替换指定内容
for key, value in data.items():
if key in paragraph.text:
inline = paragraph.runs
for i in range(len(inline)):
if key in inline[i].text:
text = inline[i].text.replace(key, str(value))
inline[i].text = text
# 保存生成的文档
template.save("output.docx")
# 使用示例
template_path = "template.docx" # 模板文件路径
data = {
"{name}": "张三",
"{age}": 25,
"{address}": "北京市"
}
generate_document(template_path, data)
在上面的示例代码中,我们使用了python-docx库来处理Word文档。程序会打开指定的模板文档,遍历模板中的每个段落,然后替换其中的指定内容。替换内容时,根据data字典中的键值对来进行替换。最后,程序会将生成的文档保存为output.docx文件。