背景: 根据每日提供的水果销售数据,按照水果分类进行销售额统计
代码段如下:
import xlrd,xlwt
from pathlib import Path,PurePath
from collections import defaultdict
#水果清单路径
src_path=r'C:\Users\think\Desktop\Python_Excel\fruit'
#获取清单下所有的xlsx文件
p = Path(src_path)
files_list = [x for x in p.iterdir() if PurePath(x).match("*.xlsx")]
#定义字典统计结果
total = defaultdict(int) #如果获取的key不存在,则值为0
#建议不要使用中文做字典的key,这里进行转换
tran_dict = {
"dragon_fruit": "火龙果",
"coconut": "椰子",
"watermelon": "西瓜",
"apple": "苹果"
}
def dict_key(value):
return [k for k,v in tran_dict.items() if v == value]
def dict_name(key):
return tran_dict[key]
# 遍历文件
for file in files_list:
#打开xlsx
sheet = xlrd.open_workbook(file)
#遍历表格
for table in sheet.sheets():
#遍历获取表格中每一行的的数据
for line in range(1,table.nrows):
#获取每一行的值组成的列表
fruit = table.row_values(rowx=line,start_colx=0,end_colx=None)
fruit_name = dict_key(fruit[0])[0]
total[fruit_name] = total[fruit_name] + fruit[-2]
for fruit_name in total:
print(f'水果: {dict_name(fruit_name)},总金额: {total[fruit_name]}')