- 論壇徽章:
- 0
|
今天應同事要求,幫她寫了一個小程序,用python寫的,統(tǒng)計一個execl文件 的特定列里的所有值的出現(xiàn)次數(shù)
代碼:
=====================================================
#!/usr/bin/env python
#coding=gbk
#此PY用來統(tǒng)計一個execl文件中的特定一列的值的分類
import win32com.client
filename=raw_input("請輸入要統(tǒng)計文件的詳細地址:")
flag=0 #用于判斷文件 名如果不帶‘日’就為 0
if '\xc8\xd5' in filename:flag=1
print 50*'='+'\n\t 請稍等,程序正在統(tǒng)計中。。。'
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'業(yè)務類型' or sheet.Cells(3,3).Value!=u'轉辦單位':
print '您輸入的表格已不是默認的表格,數(shù)據格式有誤'
exit(1) #這個判斷是當文件中的特定列改變時,直接退出程序
i=4
dept=sheet.Cells(i,3).Value
type=sheet.Cells(i,6).Value
typelist=[] #用于存放數(shù)據的列表,下面就是取sheet表里的某一列數(shù)據
deptlist=[] #用于存放轉辦單位的列表
while type:
typelist.append(type)
deptlist.append(dept)
i=i+1
type=sheet.Cells(i,6).Value
dept=sheet.Cells(i,3).Value
#存放列的數(shù)據到二個列表中
counts=len(typelist) #總件數(shù)
if counts==0:
print '輸入的文件統(tǒng)計結果為0,是否文件的格式有誤?'
exit(1)
typelist=[(i,typelist.count(i)) for i in set(typelist)]
departmentlist=[]
delchar='0123456789' #刪除取出列表中有可能帶數(shù)字 分開字段有空格的話
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信訪件總數(shù)為%d件,下面是各分類件數(shù)' % 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 '正在退出程序,請稍等。。。'
本文來自ChinaUnix博客,如果查看原文請點:http://blog.chinaunix.net/u2/82009/showart_2164358.html |
|