最近为了做点小事情,需要对12个Excel文件进行处理,每个Excel文件的数据量都非常庞大。所处理的数据是全国196个站点2000年至2011年每天的降水数据,需要根据这些数据统计出每个站点的年降水量以及每年每个月的降水量,如果纯粹采用手工操作Excel表格,显得相当的麻烦,为了简单起见,就用python写了个小程序来帮我自动实现批处理。
下面就详细的讲述整个实现过程。
1、在计算机上安装python(x,y)2.6.6版本。这一步是确保机器上的python开发环境,具体的安装过程在此就不在赘述,网上相关资料比较多
2、建议安装一个Notepad++,这样写代码比较方便
3、在Notepad++中进行相关的设置,因为python对行缩进符比较敏感,用Tab键和space键混合使用,会导致编译错误,程序无法执行;但是一般tab键和Space键所敲出来的空格是隐藏的,为了编辑方便,就需要在Notepad中将空格符显示出来。设置如下图所示。
4、安装相应的开发包,这里采用的开发包为xlrd-0.9.3包(读取excel)和xlwt-0.7.5包(存写excel,只支持.xls格式,不支持.xlsx格式,如果需要.xlsx格式,请下载更高版本的安装包)。具体的安装过程在此不再赘述,请详见点击打开链接http://blog.csdn.net/dxh0907070012/article/details/23967247。
5、为所要处理的excel文件单独建立一个文件夹。
6、具体代码如下:
#coding=utf-8
import xlrd
import xlwt
import string
import numpy as np
import os
class OperExcel():
def rExcel(self,inEfile,strfilename,outfile):
rfile=xlrd.open_workbook(inEfile)
table=rfile.sheet_by_index(0)
nrows=table.nrows-1
ncols=table.ncols
stationsheet=xlrd.open_workbook('D://rainfall_deal//stationposition.xlsx')
stationtable=stationsheet.sheet_by_index(0)
nstnrows=stationtable.nrows-1
wb=xlwt.Workbook()
ws=wb.add_sheet('year_month')
month=['1','2','3','4','5','6','7','8','9','10','11','12']
for stationindex in range(1,nstnrows):
eachday_rf=[]
yearsum=0
monthday_rf=[]
eachmon_rf=0
stncode=stationtable.cell(stationindex,0).value
#计算每个站点的年降水总量
for r in range(1,nrows):
if(table.cell(r,0).value==stncode):
strvalue=table.cell(r,4).value
eachday_rf.append(strvalue)
if(table.cell(r,0).value!=stncode):
continue
for k in range(0,len(eachday_rf)):
eachday_rainfall=int(eachday_rf[k])
yearsum=yearsum+eachday_rainfall
del(eachday_rf)
ws.write(stationindex,0,stationtable.cell(stationindex,0).value)
ws.write(stationindex,1,yearsum)
yearsum=0
#计算每个站点每个月的降水总量
for monindex in range(0,len(month)):
for r in range(1,nrows):
if(int(table.cell(r,2).value)==(monindex+1) and table.cell(r,0).value==stncode):
monthday_rf.append(table.cell(r,4).value)
for monrfindex in range(0,len(monthday_rf)):
eachmon_rf=eachmon_rf+int(monthday_rf[monrfindex])
monthday_rf=[]
ws.write(stationindex,monindex+2,eachmon_rf)
eachmon_rf=0
savepth='D://rainfall_deal'
strsavepth=savepth+'//'+strfilename
wb.save(strsavepth)
if __name__ == '__main__':
path='D://rainfall_deal//rainfall_excel'
lista=os.listdir(path)
monthname=['2000','2001','2002','2003','2004','2005','2006','2007','2008','2009','2010','2011']
for k in range(0,len(lista)):
strPth=path+'//'+lista[k]
t = OperExcel()
strfilename='stat_'+monthname[k]+'rf.xls'
t.rExcel(strPth,strfilename,'test')
7、在dos下面,执行代码。坐等收获想要的数据。
8、结果如下:
总结:python是一门很有用的语言,能帮助做不少的事情。很容易学。我的这个程序还有不少问题,还望高手指教!