展开全部
# -*- coding:utf-8 -*-
from xlrd import open_workbook
from xlutils.copy import copy
def getrule(rfile='test.txt'):
try:
rdict={}
with open(rfile,'r') as f:
for line in f:
rline=line.split('->')
rdict[rline[0].strip()]=rline[1].strip()
return rdict
except Exception,e:
print e
if __name__ == '__main__':
excelfile='test.xls'
rdict=getrule()
rb = open_workbook(excelfile)
rs = rb.sheet_by_index(0)
wb = copy(rb)
ws = wb.get_sheet(0)
nrows = rs.nrows
ncols = rs.ncols
for i in range(nrows):
for j in range(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])
wb.save(excelfile)
其中test.xls存放需替换的xls文件,62616964757a686964616fe78988e69d8331333335333639test.txt存放规则文件,代码如上。