python使用xlrd以及xlutils.copy实现替换原有xls中特定字符为指定字符

python使用xlrd以及xlutils.copy实现替换原有xls中特定字符为指定字符

import xlrd
from xlutils.copy import copy
import os
import re


'''
file:文件目录的路径
text:需要替换的字符
replacetext:期望替换成的字符
'''
def findAndReplace(file, text, replacetext):
    wb = xlrd.open_workbook(file, formatting_info=True)  # 获取xls,保留原格式
    ws = wb.sheet_by_index(0)  # 根据index获取sheet

    rows = ws.nrows
    cols = ws.ncols

    newbook = copy(wb)  # 复制xls
    newsheet = newbook.get_sheet(0)

    # 遍历每个单元格,进行替换操作
    for row in range(1, rows):
        for col in range(1, cols):
            content = ws.cell(row, col).value
            if(content != None and isinstance(content, str)):  # 判断不为空且为字符
                if(content.find(text) != -1):  # 找到需要替换的字符
                    print("修改前:" + content)
                    print("修改后" + content.replace(text, replacetext))
                    newsheet.write(row, col, content.replace(text, replacetext))
    
    # 保存新的xls以替换原有的xls
    newbook.save(file)
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值