大家好,我—python萌新一枚,今天想用python批量制作word版证书,word文档中需要替换的内容是文本框格式的,程序运行后文件批量生成了,但是文档文本框的内容并未改变,以下是部分代码,我用的是python3.8 +pycharm,请专家能帮忙解答,谢谢各位。
import os
from docx import Document
from openpyxl import load_workbook
# 提取word文本框中文本
file = Document('C:/Users/Administrator/Desktop/证书模板.docx')
children = file.element.body.iter()
wb = load_workbook('C:/Users/Administrator/Desktop/证书明细.xlsx')
sheet=wb.active
sheet.max_row
for row in range(2,sheet.max_row+1):
document = Document('C:/Users/Administrator/Desktop/证书模板.docx')
old_text1 = sheet.cell(row=1,column=1).value
old_text2 = sheet.cell(row=1,column=2).value
new_text1 = sheet.cell(row=row,column=1).value
new_text2 = sheet.cell(row=row, column=2).value
children = file.element.body.iter()
# 遍历文档每个子节点
for child in children:
# 只处理textBox
if child.tag.endswith('textbox'):
for c in child.iter():
# 进行文本替换
if c.tag.endswith('main}r'):
if c.text == old_text2:
c.text = c.text.replace(c.text, new_text2)
elif c.text == old_text1:
c.text = c.text.replace(c.text, new_text1)
filename=str(sheet.cell(row=row,column=1).value)
document.save(r'创建word版证书/{}.docx'.format(filename))
print('{}的证书已生成'.format(filename))
可以将children = file.element.body.iter()
这句改成
children = document.element.body.iter()
或者将for 循环里的第13行、第18行去掉。试试看如何。