本文實例講述了Python實現對excel文件列表值進行統計的方法。分享給大家供大家參考。具體如下:
#!/usr/bin/env python
#coding=gbk
#此PY用來統計一個execl文件中的特定一列的值的分類
import win32com.client
filename=raw_input("請輸入要統計文件的詳細地址:")
flag=0 #用于判斷文件 名如果不帶‘日'就為 0
if '\xc8\xd5' in filename:flag=1
print 50*'='+'\n\t 請稍等,程序正在統計中。。。'
try:
xls=win32com.client.Dispatch('et.Application')
try:
xlsfile=xls.Workbooks.Open(filename)
#打開指定的文件,一般打開的是sheet1
sheet=xlsfile.Worksheets('Sheet1')
except:
print '文件找開錯誤!'
exit(1)
print '程序正在自動退出。。。'
if sheet.Cells(3,6).Value!=u'業務類型' or sheet.Cells(3,3).Value!=u'轉辦單位':
print '您輸入的表格已不是默認的表格,數據格式有誤'
exit(1) #這個判斷是當文件中的特定列改變時,直接退出程序
i=4
dept=sheet.Cells(i,3).Value
type=sheet.Cells(i,6).Value
typelist=[] #用于存放數據的列表,下面就是取sheet表里的某一列數據
deptlist=[] #用于存放轉辦單位的列表
while type:
typelist.append(type)
deptlist.append(dept)
i=i+1
type=sheet.Cells(i,6).Value
dept=sheet.Cells(i,3).Value
#存放列的數據到二個列表中
counts=len(typelist) #總件數
if counts==0:
print '輸入的文件統計結果為0,是否文件的格式有誤?'
exit(1)
typelist=[(i,typelist.count(i)) for i in set(typelist)]
departmentlist=[]
delchar='0123456789' #刪除取出列表中有可能帶數字 分開字段有空格的話
for i in deptlist[:]:
i=''.join([j for j in i if j not in delchar])
while '.' in i: i=i.replace('.',' ')
deptlist+=i.split()
deptlist=deptlist[counts:]
deptlist=[(i,deptlist.count(i)) for i in set(deptlist)]
#下面是打印格式等 。。。
print '\n'+50*'='
print '\t信訪件總數為%d件,下面是各分類件數' % counts,
print '\n'+50*'='+'\n'
for i in range(len(typelist)):
print '\t',typelist[0],typelist[1],'\t',
if i % 2 ==1 : print '\n'
if flag==0:
print '\n'+50*'='+'\n\t下面是轉辦單位的分類\n'+50*'='
for i in range(len(deptlist)):
print '\t',deptlist[0],deptlist[1],'\t',
if i % 2 ==1 : print '\n'
finally:
xls.Quit()
raw_input('\n\n'+50*'='+'\n請輸入回車鍵退出程序!')
print '正在退出程序,請稍等。。。'
希望本文所述對大家的Python程序設計有所幫助。
希望與廣大網友互動??
點此進行留言吧!