批量替换word文字

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')
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值