上一篇主要针对老版本的excel文件,这一篇主要时针对新版本的excel
使用Openpyxl 模块
from openpyxl import Workbook for m in range(1,13): wb=Workbook() #新建工作簿 wb.save('%d 月.xlsx'%m) #保存工作簿
import openpyxl wb=openpyxl.load_workbook('工作簿.xlsx') #打开工作簿 for sh in wb.worksheets: sh.title=sh.title+'-随便写点啥都可以' wb.save('结果.xlsx')
import openpyxl wb = openpy.Workbook() #新建工作簿 for m in range(1,13): wb.create_sheet('%d 月'%m) wb.remove(wb['Sheet']) #删除指定工作表 wb.save('结果.xlsx')
import openpyxl wb=openpyxl.load_workbook('工作簿.xlsx') for sh in wb: if sh.title.split('-')[0]!='北京': wb.remove(sh) wb.save('结果.xlsx')
import openpyxl wb = openpyxl.load_workbook('工作簿.xlsx') for m in range(1,13): wb.copy_worksheet(wb['demo']).title='%d月'%m wb.save('结果.xlsx')
import openpyxl wb = openpyxl.load_workbook('工作簿.xlsx') sum([s['b14'].value for s in wb]))
#方法一 import openpyxl wb=openpyxl.load_workbook('工作簿.xlsx') ws=wb['工作表名称']#提起指定工作表 rng=ws['A2':'E71']#指定取数的范围 [sum([r.value for r in rn][1:]) for rn in rng] #方法二 import openpyxl wb = open[yxl.load_workbook('工作簿.xlsx') ws = wb.active for x in list(ws.value)[1:]: [x[0],sum(x[1:])]
import openpyxl wb = openpyxl.load_worlbook('工作簿.xlsx') ws = wb.active for x in list(zip(*list(ws.values)))[1:]: [x[0],float('%.2f'%(sum(x[1:])/len(x)-1))]
import openpyxl wb = openpyxl.load_workbook('工作簿.xlsx') ws = wb.active #获取当前活跃的工作表 minr=ws.ws.min_row #最小行 minc=ws.min_column #最小列 maxr=ws.max_row #最大行 maxc=ws.max_column #最大列 rngs=ws.iter_rows(min_row=minr+1,min_col=minc+2,max_row=maxr-1,max_col=maxc-1)#动态获取数据区域 subtotal =[min([v.value for v in row]) for row in rngs]
import openpyxl wb = openpyxl.load_workbook('工作簿.xlsx') wb=ws.active rngs = ws.iter_rows(min_row=2,min_col=2) for row in rngs: for c in row: if c.value>=90: c.value ='%d(%s)%(c.value,'优秀')' wb.save(结果.xlsx)
import openpyxl wb=openpyxl.load_workbook('工作簿.xlsx') ws=wb['成绩表'] nws=wb.create_sheet('结果')#创建工作表 rng=list(ws.rows)[1:] nws.append([v.value for v in ws['1':'1']]+['总分']) for l in rng: l1=[v.value for v in l] if sum(ll[1:])>=300: nws.append(l1+[sum(ll[1:])]) wb.save('结果.xlsx')
import openpyxl wb=openpuxl.load_workbook('工作簿.xlsx') nwb=openpyxl.Workbook()#新建工作簿 nws=nwb.active nws.append(['年','月','金额']) #写入标题 for sh in wb: l1=[[[sh.title]+[v.value for v in l]]for l in sh.rows][1:-1] for l in l1: nws.append(l) nwb.save('合并.xlsx')