查找目标文件夹内所有的Excel文件,按月份统计相关业务量,并输出到文本文档。
import time
import os
import xlrd
import copy
import pathlib
import datetime
import sys
import collections
def getusefile():
#查当前目录下所有xls xlsx文件,返回文件名列表
usefile=[]
excelfile=sorted(pathlib.Path('.').glob('*.xls*'))
usefile=[str(tpfile) for tpfile in excelfile]
return copy.deepcopy(usefile)
def rdusefile(fileName):
#读一个文件,并在文件单元格中查找目标数据,如果找到就返回文件名及数据
data=xlrd.open_workbook(fileName) #打开当前目录下名为 fileName 的文档
worksheets = data.sheet_names() #返回book中所有工作表的名字
#打开excel文件的第filenum张表
sheet_1=data.sheets()[0] #通过索引顺序获取sheet表
nrows=sheet_1.nrows #获取该sheet中的有效行数
ncols=sheet_1.ncols #获取该sheet中的有效列数
getdata=[]
#读取文件数据
for i in range(1,nrows-1):
tep1=[]
tep1=sheet_1.row(i)[2].value
getdata.append(tep1)
return copy.deepcopy(getdata)
newdir=os.path.join(os.getcwd(),'new')
os.chdir(newdir)
filelist=getusefile()
out=[]
for file0 in filelist:
out1={}
finddata=rdusefile(file0)
print('号码: ',file0.split('.')[0],' 总数量: ',len(finddata))
out1['haoma']=file0.split('.')[0]
out1['shuliang']=len(finddata)
findall=[cc[:7] for cc in finddata]
a=dict(collections.Counter(findall))
out1['data']=a
out.append(out1)
print(a)
print('--'*30)
with open('out1.txt','w')as f:
yue=list(out[0].get("data").keys())
ahm,asl='号码'+'\t','总数量'+'\t'
for cc in out:
ahm=ahm+cc.get('haoma')+'\t'
asl=asl+str(cc.get('shuliang'))+'\t'
f.write(ahm+'\n')
f.write(asl+'\n')
for cc in yue:
agy=cc+'\t'
for ct in out:
agy=agy+str(ct.get('data').get(str(cc)))+'\t'
f.write(agy+'\n')
输出1:
文本输出2:
关注Python开发练习,200G学习资源免费送,还可以免费处理2.5小时以内的各类小Task。