实现的目标
批量修改excel文档内容
用到的python模块
pip install jdcal
pip install et_xmlfile
pip install openpyxl
脚本内容
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | # -*- coding:gbk -*- import openpyxl import re import traceback import os path = u'G:\CMMI2020年培训拷出' def changeData(file, mode, text, replaceText): wb = openpyxl.load_workbook(file) num = 0 sheet_list = wb.sheetnames for sheet in sheet_list: ws = wb.worksheets[num] num=num+1 cols = ws.max_column rows = ws.max_row changeCells = 0 try: for row in range(1,rows+1): for col in range(1,cols+1): content = ws.cell(row=row,column=col).value if(content != None): if(mode == 1): if(content == text): ws.cell(row=row,column=col).value = replaceText elif(mode == 2): if(type(content) == str): ws.cell(row=row,column=col).value = content.replace(text,replaceText,1) elif(mode == 3): if(type(content) == str): ws.cell(row=row,column=col).value = content.replace(text,text+replaceText,1) else: print(str(mode) + " error") print(file +' ' + sheet +' 修改完成') except Exception as e: print(traceback.format_exc()) wb.save(file) if __name__ == "__main__": for parent, dirnames, filenames in os.walk(path): for fn in filenames: filedir = os.path.join(parent, fn) if fn.endswith('.xlsx'): changeData(filedir, 2, "徐延林","胡腾飞") changeData(filedir, 2, "李金","郭阔") #1. 全字匹配替换(mode1);(如:全字匹配 yocichen, 替换成为 yociXchen) #2. 部分字符匹配替换(mode2);(如:thisisyociblog,替换成为 thisisyocichenblog) #3. 全字匹配填充(mode3);(如:yoci,替换成为yoci: a foolish),用于在字符后面添加字符 |