办公自动化12-word批量替换(将替换内容写在excel里)

有些时候,需要批量替换word的内容,每次都打开‘查找替换’窗口比较繁琐,这个时候我们可以把想要替换的内容放在excel里,如下图

然后通过代码实现word批量替换。

import xlrd
from docx import Document
#1.excel转化为dict
dir_case = 'C:\Users\17360\Desktop\test.xlsx' #存放替换内容的excel地址
data = xlrd.open_workbook(dir_case)
table = data.sheets()[0]#数据是存放在excel的第一个sheet
nor = table.nrows
nol = table.ncols
dict1 = {}
for i in range(1,nor):
    for j in range(nol):
        title = table.cell_value(0,j)
        value = table.cell_value(i,j)
        dict1[title] = value
#2.word批量替换
def check_and_change(document, replace_dict):
    """
    遍历word中的所有 paragraphs,在每一段中发现含有key 的内容,就替换为 value 。 
    (key 和 value 都是replace_dict中的键值对。)
    """
    for para in document.paragraphs:
        for i in range(len(para.runs)):
            for key, value in replace_dict.items():
                if key in para.runs[i].text:
                    print(key+"-->"+value)
                    para.runs[i].text = para.runs[i].text.replace(key, value)
    return document
old_file = 'C:\Users\17360\Desktop\test.docx'
new_file = 'C:\Users\17360\Desktop\test1.docx'
document = Document(old_file)
document = check_and_change(document, dict1)
document.save(new_file)

备注:如果想要替换数字的话,需要在excel里将数字格式设置为‘文本’哦

有问题欢迎留言^_^

原文地址:https://www.cnblogs.com/lizitingxue/p/12576871.html