python 修改excel

from xlrd import open_workbook
from xlutils.copy import copy
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

def replaceexcel(file_path,replacedic):

# 0 based (subtract 1 from excel row number)
START_ROW = 1
ismal_index = 0

#formatting_info=True保存之前数据的格式
rb = open_workbook(file_path,formatting_info=True)
r_sheet = rb.sheet_by_index(0) # read only copy to introspect the file
wb = copy(rb) # a writable copy (I can't read values out of this, only write to it)
w_sheet = wb.get_sheet(0) # the sheet to write to within the writable copy


#r_sheet.nrows为总行数
for row_index in range(START_ROW, r_sheet.nrows):
newcellvalue = ''
oldcellvalue = r_sheet.cell_value(row_index,0)
if isinstance(oldcellvalue, (str, unicode)):
oldcellvalue = oldcellvalue.replace(' ','')
try:
findnum = oldcellvalue.find('_')
findstr = oldcellvalue[:findnum]
newcellvalue = replacedic[oldcellvalue[:findnum]]+oldcellvalue[findnum:]
except:
newcellvalue = oldcellvalue
print newcellvalue,oldcellvalue
w_sheet.write(row_index, ismal_index,newcellvalue)

wb.save(file_path)

file_path = "C:\\Users\\Administrator\\Desktop\\test.xls"
dic = {'111':u"牛逼2",'222':u"大龙2"}
replaceexcel(file_path,dic)
posted @ 2017-02-17 00:12  aloneOnWorld  阅读(2028)  评论(0编辑  收藏  举报