首页 > 其他分享 >批量替换doc、xls、xlsx文件内容

批量替换doc、xls、xlsx文件内容

时间:2024-07-04 14:41:46浏览次数:13  
标签:xlsx old string doc cell file path new xls

docx类:

import os
from docx import Document
from openpyxl import load_workbook

def replace_string_in_docx(file_path, old_string, new_string):
    doc = Document(file_path)
    for paragraph in doc.paragraphs:
        if old_string in paragraph.text:
            paragraph.text = paragraph.text.replace(old_string, new_string)
    doc.save(file_path)

def replace_string_in_xlsx(file_path, old_string, new_string):
    wb = load_workbook(filename = file_path)
    for sheet in wb:
        for row in sheet.iter_rows():
            for cell in row:
                if cell.value and old_string in str(cell.value):
                    cell.value = cell.value.replace(old_string, new_string)
    wb.save(file_path)

def replace_string_in_files(dir_path, old_string, new_string):
    for root, dirs, files in os.walk(dir_path):
        for file in files:
            if file.endswith('.doc'):
                replace_string_in_docx(os.path.join(root, file), old_string, new_string)
            elif file.endswith('.xls'):
                replace_string_in_xlsx(os.path.join(root, file), old_string, new_string)

replace_string_in_files('C:\\Users\\dir',  'old', 'new')

doc

import os
import win32com.client
import datetime

def replace_string_in_doc(file_path, old_string, new_string):
    word = win32com.client.Dispatch("Word.Application")
    doc = word.Documents.Open(file_path)
    word.Visible = 0
    replacement_count = 0
    for i in range(len(doc.Paragraphs)):
        para = doc.Paragraphs[i]
        if old_string in para.Range.Text:
            replacement_count += para.Range.Text.count(old_string)
            para.Range.Text = para.Range.Text.replace(old_string, new_string)
    doc.Save()
    doc.Close()
    return replacement_count

def replace_string_in_xls(file_path, old_string, new_string):
    excel = win32com.client.Dispatch("Excel.Application")
    workbook = excel.Workbooks.Open(file_path)
    excel.Visible = 0
    replacement_count = 0
    for worksheet in workbook.Worksheets:
        for row in worksheet.UsedRange.Rows:
            for cell in row.Cells:
                if cell.Value:
                    if isinstance(cell.Value, datetime.datetime):
                        cell_value_str = cell.Value.strftime('%m/%d/%Y')
                        if old_string == cell_value_str:
                            replacement_count += 1
                            cell.Value = datetime.datetime.strptime(new_string, '%m/%d/%Y')
                    else:
                        cell_value_str = str(cell.Value)
                        if old_string in cell_value_str:
                            replacement_count += cell_value_str.count(old_string)
                            cell.Value = cell_value_str.replace(old_string, new_string)
    workbook.Save()
    workbook.Close()
    return replacement_count

def replace_string_in_files(dir_path, old_string, new_string):
    for root, dirs, files in os.walk(dir_path):
        for file in files:
            if file.endswith('.doc'):
                print(f"Processing {file}...")
                replacement_count = replace_string_in_doc(os.path.join(root, file), old_string, new_string)
                print(f"Replaced '{old_string}' with '{new_string}' {replacement_count} times in {file}")
            elif file.endswith('.xls'):
                print(f"Processing {file}...")
                replacement_count = replace_string_in_xls(os.path.join(root, file), old_string, new_string)
                print(f"Replaced '{old_string}' with '{new_string}' {replacement_count} times in {file}")

replace_string_in_files('C:\\Users\\dir',  'old', 'new')

标签:xlsx,old,string,doc,cell,file,path,new,xls
From: https://www.cnblogs.com/alfredsun/p/18283826

相关文章

  • 构建阿里云的centos7-docker镜像
    最近在项目中需要测试运维脚本,但是在网上都找不到可以模拟阿里云的centos7镜像,所以就自己构建了一个,跟大家分享下。构建平台:操作系统window11软件dockerdesktop工作目录:CentOS-Base.repo[base]name=CentOS-$releaseverenabled=1failovermethod=prioritybaseurl......
  • 【中国工程院院士、IEEE Fellow等大咖云集】第六届复杂系统数据驱动优化国际会议(DOCS
    第六届复杂系统数据驱动优化国际会议(DOCS2024)将于2024年8月16-18日在中国杭州召开,组委会诚挚邀请与复杂系统数据驱动优化相关的广泛领域的研究人员、从业人员和学者踊跃投稿、积极参会交流。1.会议官方会议官网:www.ic-docs.org时间地点:2024年8月16-18日中国-......
  • 【Docker安装】OpenEuler系统下部署Docker环境
    【Docker安装】OpenEuler系统下部署Docker环境前言一、本次实践介绍1.1本次实践规划1.2本次实践简介二、检查本地环境2.1检查操作系统版本2.2检查内核版本2.3检查yum仓库三、卸载Docker四、部署Docker环境4.1配置yum仓库4.2检查可用yum仓库......
  • jdk的Dockerfile构建
    JDKFROMcentos:[email protected]#时间更新RUN/bin/cp/usr/share/zoneinfo/Asia/Shanghai/etc/localtime\&&echo'Asia/Shanghai'>/etc/timezone#仓库源配置RUNrm-rf/etc/yum.repos.d/*.repo\&&curl......
  • Docker自定义网络的好处
    docker基础(19):Docker网络之自定义网络_docker创建自定义网络-CSDN博客docker0网络特点他是默认的域名访问不通(有些应用是需要配置域名,或许写死ip配置就不够灵活)–link域名通了,但是删除了又不行docker--link容器互联_dockerlink-CSDN博客 简单点说,自定义网络的好处是不用......
  • Docker top和stats区别
    dockertop需要指定容器,且不是动态显示容器资源使用情况dockerstats动态打印所有容器资源使用情况[root@localhost~]#dockertop--helpUsage:dockertopCONTAINER[psOPTIONS]DisplaytherunningprocessesofacontainerAliases:dockercontainertop,do......
  • Docker 目录挂载和卷映射
    docker卷和目录的区别_docker挂载和映射的区别-CSDN博客linuxdocker目录挂载映射_linux创建网关docker映射目录-CSDN博客因为容器是无状态,rm掉就不报错数据,所以需要-v挂载到宿主机上路径:使用绝对路径的是目录挂载-v/usr/local/www:/opt/html使用相对路径的是卷映射-v......
  • Windows 安装docker详细步骤说明
    目录1.检查系统要求2.启用硬件虚拟化3.启用Hyper-V和容器功能4.下载并安装DockerDesktop5.配置DockerDesktop6.安装WSL27.验证Docker安装8.常见问题排查9.重点说明参考资源在Windows上安装Docker的详细步骤如下:1.检查系统要求确保您的Windows系统满足以下要求:Wi......
  • IDEA连接docker
    修改配置文件vi/usr/lib/systemd/system/docker.service修改ExecStart为ExecStart=/usr/bin/dockerd-Hfd://--containerd=/run/containerd/containerd.sock--tlsverify--tlscacert=/etc/ docker/certs/ca.pem--tlscert=/etc/docker/certs/server-cert.pem--tlskey=/......
  • 容器技术-docker5
    一、docker-compose常用命令和指令1.概要默认的模板文件是docker-compose.yml,其中定义的每个服务可以通过image指令指定镜像或build指令(需要Dockerfile)来自动构建。注意如果使用build指令,在Dockerfile中设置的选项(例如:CMD,EXPOSE,VOLUME,ENV等)将会自......