Python批量替换Excel和Word中的关键字

一、问题的提出

有时,我们手头上有多个Excel或者Word文件,但是领导突然要求对某几个术语进行批量的修改,你是不是有要崩溃的感觉。因为这么多文件,要一个一个地打开文件,再进行批量替换修改,几个文件还好,如果是成百上千的文件,我想你一会儿就感觉自己被搞晕了,不仅搞不清修改了没有修改完,而且已经修改的也不知道修改的彻底不。

于是,问题来了,当我需要对多个Excel和Word文件中的关键字进行替换,而且不改变原文件的格式,同时删除源文件,我们该怎么办?这些office文件可能分布在不同的文件夹下,所以替换后还要存放在原来的文件夹。同时,我们编写的程序还要在Windows和MacOS环境下都可以使用。

二、算法分析

由于要在多个环境下使用,我们放弃VBA,考虑采用Python编程的方法来解决。

1. 第一步 读取一个替换关键字的"批量替换表.xlsx"生成一个字典,这样是为了后面可以批量替换。第二步 遍历当前目录下所有目录包括上当的文件,主要是docx和xlsx文件,如果是doc和xls文件,还要考虑两这两种格式的文件进行批量的转化,见下面的文章 。

批量转doc和xls为docx和xlsx文件

2. 第二步是 遍历当前所有目录中的文件,用if条件,根据文件扩展名的不同来筛选出docx和xlsx文件。代码如下:

python 复制代码
    for root, filefolder, files in os.walk(os.curdir):
        for file in files:
            if file.endswith("docx"):
                file_path = os.path.join(root, file)
                for key, value in dic.items():
                    word_replace_keywords(file_path, key, value)
            elif file.endswith("xlsx") and os.path.basename(file)!="批量替换表.xlsx":
                file_path = os.path.join(root, file)
                for key, value in dic.items():
                    excel_replace_keywords(file_path, key, value)

3. 第三步是对于docx和xlsx文件分别进行替换处理,主要采用了python-docx和openpyxls这两个模块来进行替换。针对docx文件,我们用Document()来读取,用以下代码来替换:

python 复制代码
def info_update(doc, old, new):
    for para in doc.paragraphs:
        for run in para.runs:
            if old in run.text:
                run.text = run.text.replace(old, new)

对于xlsx文件我,我们通过下面的代码实现关键字替换,同时不改变原来关键字的格式。

python 复制代码
def replace_cell_text_with_format(cell, keyword, replacement):
    paragraphs = cell.paragraphs
    for paragraph in paragraphs:
        for run in paragraph.runs:
            if keyword in run.text:
                new_text = run.text.replace(keyword, replacement)
                run.clear()  # 清除当前文本
                new_run = run._element  # 创建新的run
                new_run.text = new_text  # 设置新文本
                for key in run._r.attrib.keys():  # 复制格式属性
                    if key != 't':
                        new_run.attrib[key] = run._r.attrib[key]

4. 第四步 我们要保存替换后的文件,同时用os.remove()删除原来的文件。

三、代码展示

最终,我们编制出70多行的代码,一键实现了多文件、多关键字、保存源格式,又能在Windows和苹果电脑环境使用的程序。代码如下:

python 复制代码
import os
from docx import Document
from openpyxl import load_workbook

def info_update(doc, old, new):
    for para in doc.paragraphs:
        for run in para.runs:
            if old in run.text:
                run.text = run.text.replace(old, new)
                
def replace_cell_text_with_format(cell, keyword, replacement):
    paragraphs = cell.paragraphs
    for paragraph in paragraphs:
        for run in paragraph.runs:
            if keyword in run.text:
                new_text = run.text.replace(keyword, replacement)
                run.clear()  # 清除当前文本
                new_run = run._element  # 创建新的run
                new_run.text = new_text  # 设置新文本
                for key in run._r.attrib.keys():  # 复制格式属性
                    if key != 't':
                        new_run.attrib[key] = run._r.attrib[key]
def get_dic():
    workbook = load_workbook('批量替换表.xlsx')
    sht = workbook.active
    dic = {}
    for c1,c2 in zip(sht["A"],sht["B"]):
        if c1.value!= None and c2.value!= None:
            dic[c1.value] = c2.value
    return dic

def word_replace_keywords(file_path, keyword, replacement):
    doc = Document(file_path)
    info_update(doc, keyword, replacement)
    try: 
        for table in doc.tables:
            if not any(cell.text for row in table.rows for cell in row.cells):
                continue  
            for row in table.rows:
                for cell in row.cells:
                    if keyword in cell.text:
                        replace_cell_text_with_format(cell, keyword, replacement)
    except Exception as e:
        print("Error processing table:", e)
            
    doc.save(file_path)

def excel_replace_keywords(file_path, keyword, replacement):
    wb = load_workbook(file_path)
    for sheet_name in wb.sheetnames:
        sheet = wb[sheet_name]
        for row in sheet.iter_rows():
            for cell in row:
                if cell.value and keyword in str(cell.value):
                    cell.value = str(cell.value).replace(keyword, replacement)
    wb.save(file_path)
    wb.close()
    
def get_replaced(dic):    
    for root, filefolder, files in os.walk(os.curdir):
        for file in files:
            if file.endswith("docx"):
                file_path = os.path.join(root, file)
                for key, value in dic.items():
                    word_replace_keywords(file_path, key, value)
            elif file.endswith("xlsx") and os.path.basename(file)!="批量替换表.xlsx":
                file_path = os.path.join(root, file)
                for key, value in dic.items():
                    excel_replace_keywords(file_path, key, value)
def main():
    dic = get_dic()
    get_replaced(dic)
if __name__ == "__main__":
    main()

以上代码的优势在于:速度快,设置好关键字后一键替换,可以在多个环境下使用,相比VBA代码,Python代码的执行速度更快、操作更简单、省时省力。

四、注意事项

  1. 运行代码前一定要安装Python3.9及以上版本,同时安装openpyxl和python-docx两个模块。

  2. 执行程序前要把doc和xls文件分别转化为docx和xlsx文件,这样更方便替换。

  3. 执行前要在程序文件目录下建立一个xlsx文件,命名为"批量替换表.xlsx",在表的A列放上要查找的关键字,B列放要替换的关键字。

  4. 如果有问题,可以随时与我联系,也可以通过下面进行提问。

相关推荐
亿牛云爬虫专家37 分钟前
Kubernetes下的分布式采集系统设计与实战:趋势监测失效引发的架构进化
分布式·python·架构·kubernetes·爬虫代理·监测·采集
蹦蹦跳跳真可爱5895 小时前
Python----OpenCV(图像増强——高通滤波(索贝尔算子、沙尔算子、拉普拉斯算子),图像浮雕与特效处理)
人工智能·python·opencv·计算机视觉
nananaij5 小时前
【Python进阶篇 面向对象程序设计(3) 继承】
开发语言·python·神经网络·pycharm
雷羿 LexChien5 小时前
从 Prompt 管理到人格稳定:探索 Cursor AI 编辑器如何赋能 Prompt 工程与人格风格设计(上)
人工智能·python·llm·编辑器·prompt
敲键盘的小夜猫6 小时前
LLM复杂记忆存储-多会话隔离案例实战
人工智能·python·langchain
高压锅_12206 小时前
Django Channels WebSocket实时通信实战:从聊天功能到消息推送
python·websocket·django
胖达不服输7 小时前
「日拱一码」020 机器学习——数据处理
人工智能·python·机器学习·数据处理
吴佳浩7 小时前
Python入门指南-番外-LLM-Fingerprint(大语言模型指纹):从技术视角看AI开源生态的边界与挑战
python·llm·mcp
UrbanJazzerati8 小时前
使用Excel制作多类别占比分析字母饼图
excel
吴佳浩8 小时前
Python入门指南-AI模型相似性检测方法:技术原理与实现
人工智能·python·llm