python批量替换Excel中内容

本文介绍了一个Python脚本,该脚本能够读取文本文件中定义的替换规则,并将这些规则应用于Excel表格数据中指定单元格的内容替换。此外,还展示了如何使用正则表达式进行字符串替换,提供了实际操作示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


# -*- coding:utf-8 -*-
from xlrd import open_workbook
from xlutils.copy import copy
import re



def getrule(rfile='D:/test1.txt'):
    try:
        rdict = {}
        with open(rfile, 'r') as f:
            for line in f:
                rline = line.split('->')
                rdict[rline[0].strip()] = rline[1].strip()
                print rdict[rline[0].strip()]
        return rdict
    except Exception, e:
        print e


if __name__ == '__main__':
    excelfile = 'D:/test1.xls'
    rdict = getrule()
    print rdict
    rb = open_workbook(excelfile)
    rs = rb.sheet_by_index(0)
    wb = copy(rb)
    ws = wb.get_sheet(0)
    nrows = rs.nrows
    ncols = rs.ncols
    table = rb.sheets()[0]
    prices = table.row_values(0)[0]
    print prices
    c = prices.replace('1', '88')
    print c

    strinfo = re.compile('1')
    b = strinfo.sub('python', prices)
    print b
    for i in range(0,nrows):
        for j in range(0,ncols):
            cvalue = rs.cell(i, j).value
            # if type(cvalue).__name__ == 'float':
            #     cvalue = str(int(cvalue))
            # if rdict.has_key(cvalue):
            #     print '%s is replaced by %s' % (cvalue, rdict[cvalue])
            #     ws.write(i, j, rdict[cvalue])
            for repStr in rdict.keys():
                cvalue = cvalue.replace(repStr, rdict[repStr])
                ws.write(i, j, cvalue)
    wb.save(excelfile)
    print 'OK!'



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值