Python 實現Excel自動化辦公《中》

在Python 實現Excel自動化辦公《上》的基礎上進行一些特殊的處理,這裡的特殊處理主要是涉及到了日期格式資料的處理(上一篇文章大家估計也看到了日期資料的處理是不對的)以及常用的聚合資料統計處理,可以有效的實現你的常用統計要求。

程式碼如下:

#統計員工男女比例def get_sex_percent(): sexlist=[] for rows in range(table。nrows-1): sexlist。append(table。cell(rows+1,2)。value) print(sexlist) print(“the 男女比 is:”,round(sexlist。count(“男”)/sexlist。count(“女”),2))

輸出結果為:[‘男’, ‘女’, ‘男’, ‘男’, ‘男’, ‘男’, ‘男’, ‘女’, ‘女’, ‘男’, ‘男’, ‘女’, ‘男’, ‘男’, ‘男’, ‘女’, ‘男’, ‘女’, ‘男’, ‘男’]the 男女比 is: 2。33

#時間資料型別的處理def get_date(): for rows in range(table。nrows): for cols in range(table。ncols): if(table。cell(rows,cols)。ctype==3): date=xlrd。xldate_as_datetime(table。cell(rows,cols)。value,0) print(date)

#最後一列資料統計處理def get_statics(): sum=0 list1=[] for rows in range(table。nrows-1): sum+=int(table。cell(rows+1,table。ncols-1)。value) list1。append(int(table。cell(rows+1,table。ncols-1)。value)) # print(table。cell(rows+1,8)。value) print(“the sum is:”,sum) #求和 print(“the avg is:”, round(sum /table。ncols, 2)) #取平均值 print(“the max is:”,sorted(list1)[-1]) #取最大值 print(“the min is:”,sorted(list1)[0]) #取最小值 if(len(list1)%2==0): #判斷列表長度是奇還是偶,來取中位數 print(“the median is:”,(list1[int(len(list1)/2)]+list1[int(len(list1)/2+1)])/2) else: print(“the median is:”,list1[int((len(list1)+1)/2)])if __name__ == ‘__main__’: get_date() get_statics()

以上兩個方法程式碼執行效果如下:

Python 實現Excel自動化辦公《中》