from docx import Document
def read_ducment(old, new):
# 遍历文档
for paragraph in document.paragraphs:
for run in paragraph.runs:
# 替换功能
if old in run.text:
run.text = run.text.replace(old, new)
# 遍历表格
for table in document.tables:
for row in table.rows:
for cell in row.cells:
# 遍历表格段落内容,回到上个步骤,将cell当作paragraph处理
for paragraph in cell.paragraphs:
for run in paragraph.runs:
# 替换功能
if old in cell.text:
run.text = run.text.replace(old, new)
replacements = [('A', "11"), ('B', "22"), ('C', "33"), ('D', "44")]
document = Document(r'C:\实在智能高级认证\0-考试资料\成绩单模版 - 副本.docx')
for old, new in replacements:
read_ducment(old, new)
document.save(r'C:\实在智能高级认证\0-考试资料\成绩单模版 - 副本.docx')
批量替换word文字
于 2024-01-15 10:28:54 首次发布