Excel模板批量文本替换工具
功能说明
批量替换 .xlsm Excel模板文件中的指定文本,包括:
- 自定义功能区/菜单栏名称
- 工作表中的文本内容
实现原理
.xlsm 文件本质是 ZIP 压缩包,内含多个 XML 文件:
customUI/customUI.xml- 自定义功能区配置xl/sharedStrings.xml- 工作表共享文本
脚本通过解压→替换XML内容→重新打包的方式实现批量修改。
使用方法
编辑
replace_text.py,修改配置区的变量:old_text = '原文本' # 要替换的文本 new_text = '新文本' # 替换后的文本运行脚本:
python replace_text.py# -*- coding: utf-8 -*- """ Excel模板批量文本替换工具 用法:修改下方的 old_text 和 new_text,然后运行脚本 """ import zipfile import os import shutil import sys sys.stdout.reconfigure(encoding='utf-8') # ========== 配置区 ========== files = [ '1001银行模板(划线注销11项).xlsm', '1001银行模板(填无注销11项).xlsm', '2001往来模板.xlsm', '3001其他模板.xlsm' ] old_text = '中兴财光华' # 要替换的原文本 new_text = '审计五组' # 替换后的新文本 # ============================ for file in files: if not os.path.exists(file): print(f'文件不存在: {file}') continue print(f'处理文件: {file}') temp_dir = f'temp_{file}' # 解压xlsm文件(本质是zip包) with zipfile.ZipFile(file, 'r') as zip_ref: zip_ref.extractall(temp_dir) # 遍历所有xml文件进行文本替换 replaced_count = 0 for root, dirs, filenames in os.walk(temp_dir): for filename in filenames: if filename.endswith(('.xml', '.rels')): filepath = os.path.join(root, filename) try: with open(filepath, 'r', encoding='utf-8') as f: content = f.read() if old_text in content: new_content = content.replace(old_text, new_text) with open(filepath, 'w', encoding='utf-8') as f: f.write(new_content) replaced_count += 1 print(f' 替换: {os.path.relpath(filepath, temp_dir)}') except: pass # 重新打包为xlsm backup_file = file + '.bak' shutil.move(file, backup_file) with zipfile.ZipFile(file, 'w', zipfile.ZIP_DEFLATED) as zipf: for root, dirs, filenames in os.walk(temp_dir): for filename in filenames: filepath = os.path.join(root, filename) arcname = os.path.relpath(filepath, temp_dir) zipf.write(filepath, arcname) shutil.rmtree(temp_dir) os.remove(backup_file) print(f' 完成,替换了 {replaced_count} 处\n') print('全部处理完成!')
依赖
- Python 3.x
- 无需额外安装库(使用标准库 zipfile)


评论 (0)