python批量替换Excel中内容


# -*- 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!'



你可能感兴趣的:(Python)