吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 1889|回复: 23
收起左侧

[Python 原创] excel的内容批量替换存为新的excel文件

  [复制链接]
Codeliu 发表于 2025-7-24 16:08
本帖最后由 Codeliu 于 2025-7-24 17:50 编辑

自己有业务需求写了个py的小工具,可以吧自己的excel替换文字后重新保存到当前exe的路径


对应的代码在这边 基于pyqt的
[Python] 纯文本查看 复制代码
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import (QApplication, QWidget, QPushButton, QLineEdit, QLabel, QFileDialog,
                             QTableWidget, QTableWidgetItem, QVBoxLayout, QHBoxLayout)
from openpyxl import load_workbook
import sys

class ExcelReplaceTool(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Excel 文字替换工具")
        # self.setWindowIcon(QIcon("icon.ico"))  # 设置窗口图标
        self.init_ui()

    def init_ui(self):
        layout = QVBoxLayout()

        # 输入文件
        input_layout = QHBoxLayout()
        self.input_path = QLineEdit()
        btn_input = QPushButton("选择文件")
        btn_input.clicked.connect(self.select_input)
        input_layout.addWidget(QLabel("输入文件:"))
        input_layout.addWidget(self.input_path)
        input_layout.addWidget(btn_input)

        # 输出文件
        output_layout = QHBoxLayout()
        self.output_path = QLineEdit()
        output_layout.addWidget(QLabel("保存的文件名:"))
        output_layout.addWidget(self.output_path)

        # 替换表格
        self.table = QTableWidget(5, 2)
        self.table.setHorizontalHeaderLabels(["原文字", "新文字"])

        # 替换按钮
        replace_btn = QPushButton("开始替换")
        replace_btn.clicked.connect(self.run_replace)

        # 状态栏
        self.status = QLabel("就绪")

        layout.addLayout(input_layout)
        layout.addLayout(output_layout)
        layout.addWidget(self.table)
        layout.addWidget(replace_btn)
        layout.addWidget(self.status)
        self.setLayout(layout)

    def select_input(self):
        fname, _ = QFileDialog.getOpenFileName(self, "选择Excel文件", "", "Excel Files (*.xlsx)")
        if fname:
            self.input_path.setText(fname)

    def get_replacements(self):
        replacements = {}
        for row in range(self.table.rowCount()):
            old_item = self.table.item(row, 0)
            new_item = self.table.item(row, 1)
            if old_item and new_item:
                old_text = old_item.text().strip()
                new_text = new_item.text().strip()
                if old_text and new_text:
                    replacements[old_text] = new_text
        return replacements

    def run_replace(self):
        input_file = self.input_path.text()
        output_file = self.output_path.text()
        replacements = self.get_replacements()

        if not input_file or not output_file or not replacements:
            self.status.setText("请填写完整信息")
            return

            # 自动添加 .xlsx 扩展名(如果没有)
        if not output_file.lower().endswith('.xlsx'):
            output_file += '.xlsx'
            self.output_path.setText(output_file)  # 更新输出文件路径显示

        try:
            self.replace_chinese_in_excel(input_file, output_file, replacements)
            self.status.setText(f"替换完成!保存至 {output_file}")
        except Exception as e:
            self.status.setText(f"发生错误:{str(e)}")

    def replace_chinese_in_excel(self, input_file, output_file, replacements):
        wb = load_workbook(input_file)
        replaced = False  # 标记是否发生了替换
        for sheet in wb:
            for row in sheet.iter_rows():
                for cell in row:
                    if cell.value and isinstance(cell.value, str):
                        original_value = cell.value
                        for old_text, new_text in replacements.items():
                            if old_text in cell.value:
                                cell.value = cell.value.replace(old_text, new_text)
                                replaced = True  # 只要有一个替换,标记为 Tr
                            # 如果替换了内容,更新单元格值(可选)
                            if cell.value != original_value:
                                cell.value = cell.value
        if not replaced:
            raise Exception("未找到任何匹配的原文字,替换未执行")
        wb.save(output_file)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    tool = ExcelReplaceTool()
    tool.show()
    sys.exit(app.exec_())

蓝奏云的链接在这里 :更新了一下打包的问题(之前的打包没有吧dll打包进去,大家换一下这个就可以了,不好意思哈大家)

https://wwau.lanzouo.com/i7hlT31s8trc

原始文件

原始文件

替换后

替换后

工具

工具

免费评分

参与人数 5吾爱币 +11 热心值 +4 收起 理由
苏紫方璇 + 7 + 1 欢迎分析讨论交流,吾爱破解论坛有你更精彩!
jnct + 1 谢谢@Thanks!
wuloveyou + 1 + 1 我很赞同!
zylz9941 + 1 + 1 谢谢@Thanks!
cioceo + 1 + 1 谢谢@Thanks!

查看全部评分

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

 楼主| Codeliu 发表于 2025-7-24 16:43
本帖最后由 Codeliu 于 2025-7-24 17:51 编辑

更新了 链接 https://wwau.lanzouo.com/i7hlT31s8trc  之间是dll没有打包进去不好意思,大家可以再下载测试一下
 楼主| Codeliu 发表于 2025-7-24 16:52
刚刚看了一下 如果双击打开有LoadLibrary:找不到指定的模块   类似这个报错,可能是用户电脑没有 Visual C++的dll 这种导致的,要等等我修改下代码逻辑这种应该才可以;常规如果是安装了的话是可以的
fzh2618182 发表于 2025-7-24 16:34
wuloveyou 发表于 2025-7-24 16:35
楼主,你封装的这个PY,EXE打开会报错,LoadLibrary:找不到指定的模块    需要用到什么PIP库嘛?
cioceo 发表于 2025-7-24 16:36
这个只能替换单个文件,可以改为多个文件替换吗?
单个文件可以直接在表格中选替换,范围选工作薄
 楼主| Codeliu 发表于 2025-7-24 16:39
wuloveyou 发表于 2025-7-24 16:35
楼主,你封装的这个PY,EXE打开会报错,LoadLibrary:找不到指定的模块    需要用到什么PIP库嘛?

可以截个图嘛 我这边windows10下面应该是没问题的 常规的pyqt5和openpyxl这个处理的就好了
 楼主| Codeliu 发表于 2025-7-24 16:40
fzh2618182 发表于 2025-7-24 16:34
下载后不会使用,打开不了。

不会吧 我做个压缩吧 替换下下载链接呢
 楼主| Codeliu 发表于 2025-7-24 16:41
cioceo 发表于 2025-7-24 16:36
这个只能替换单个文件,可以改为多个文件替换吗?
单个文件可以直接在表格中选替换,范围选工作薄

多文件有在考虑写这个;单文件多个工作簿这个要花点时间去处理,理论上都可以实现的
头像被屏蔽
Sheng3qj7 发表于 2025-7-24 16:47
提示: 作者被禁止或删除 内容自动屏蔽
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - 52pojie.cn ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2026-7-14 22:54

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表