问题: 给出多个excel表,统计这些表中人员参加的情况
准备
利用模块:xlrd 1.2.0,2.x版本貌似不支持xlsx文件了
pip安装:
pip install xlrd==1.2.0
思路
- 读取指定目录的文件列表,并筛选出xlsx、xls结尾的文件列表
- 读取excel表,从中找出姓名那一列
- 向字典中插入新的键值对或已有键的情况下++
- 打印结果
代码
import os
import xlrd #最新的xlrd不行,需要用1.2.0版本的
# 获取文件列表
path = '.'
files = os.listdir(path)
fileList = []
for f in files:
if os.path.isfile(path+'/'+f) and f.split('.')[-1] in ['xlsx','xls']:
fileList.append(path+'/'+f)
print('读取到'+str(len(fileList))+'张表')
res = dict()
for f in fileList:
workbook = xlrd.open_workbook(f)
sheet = workbook.sheet_by_index(0) #得到第一张表
cols = sheet.ncols #得到列数
for i in range(cols):
print(sheet.col_values(i)[0])
if sheet.col_values(i)[0].replace(' ','')=='姓名':
print(f+'已找到姓名')
for name in sheet.col_values(i):
name = name.replace(' ','')
res[name] = 1 if name not in res.keys() else res[name]+1
break #已找到这张表中的目标列,跳过分析后面的列
for name in res.keys():
print(name+','+str(res[name]))