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