import os from openpyxl import Workbook #pip install openpyxl from openpyxl import load_workbook
ex={}#字典
defreadexcel(file): wb=load_workbook(file)#读取excel sheet=wb.get_sheet_by_name(wb.get_sheet_names()[0])#读第一个sheet表单 print("正在打开"+file+"的"+sheet.title) ws=wb.active#激活 #找一找学号在第几列 for i inrange(5): nav=[] for cell inlist(sheet.rows)[i]: nav.append(cell.value) #print(nav) if"学号"in nav:#!!!确保键值存在,且前后没有空格 break try: index=nav.index("学号") except: print("Not find key!") return; #读数据 for row inlist(sheet.rows)[i:]: rr=[] for cell in row: rr.append(cell.value) if rr[index] in ex.keys(): ex[rr[index]].extend(rr) else: ex[rr[index]]=rr
defsavefile(f): path=os.getcwd()+'/'+f if(os.path.exists(path)): print("Error!File exists.Please delete it!") return; wb=Workbook() ws = wb.active # 默认第一个sheet for i in ex: ws.append(ex[i]) wb.save(f)
defmain(): contents=[] #文件名,不要路径 files=['1.xlsx','2.xlsx','3.xlsx'] for f in files: readexcel(f) #print(ex) endfile="总结.xlsx" print("正在保存到:"+os.getcwd()+"/"+endfile) savefile(endfile)