数据汇总的第一个案例:数据汇总

原始数据:

格式为xls格式:

 代码如下:

import xlrd
from xlutils.copy import copy

def read_data():
wb = xlrd.open_workbook('C:/Users/admin/Desktop/baihuo.xls')
sh = wb.sheet_by_index(0)
fen_type = {} #{a:110,b:300}
count_price = [] #[1,2,3,4,5]

for r in range(sh.nrows):
count = sh.cell_value(r,3) * sh.cell_value(r,4)
count_price.append(count)
key = sh.cell_value(r,0)
if fen_type.get(key):
fen_type[key] += count
else:
fen_type[key] = count
return fen_type,count_price ####各分类的总价值,每个单品的总价值


def save(fen,count):
wb = xlrd.open_workbook('C:/Users/admin/Desktop/baihuo.xls')
sh_t = wb.sheet_by_index(0)
wb2 = copy(wb)
sh = wb2.get_sheet(0)
for r in range(sh_t.nrows):
sh.write(r,sh_t.ncols,count[r])
sh2 = wb2.add_sheet('汇总的数据')
for i,key in enumerate(fen.keys()):
sh2.write(i,0,key)
sh2.write(i,1,fen.get(key))
wb2.save('C:/Users/admin/Desktop/汇总数据.xls')

if __name__ == "__main__":
f,c = read_data()
save(f,c)

实现效果:

 

遇到的坑:

表格格式不兼容,不支持

File "C:/Users/admin/PycharmProjects/pythonProject/数据汇总案例1.py", line 5, in read_data
wb = xlrd.open_workbook('C:/Users/admin/Desktop/baihuo.xlsx')
File "D:\softfiles\Python3.8解释器\lib\site-packages\xlrd\__init__.py", line 170, in open_workbook
raise XLRDError(FILE_FORMAT_DESCRIPTIONS[file_format]+'; not supported')
xlrd.biffh.XLRDError: Excel xlsx file; not supported

 改完xls格式就可以了,问题得到解决

D:\softfiles\Python3.8解释器\python.exe C:/Users/admin/PycharmProjects/pythonProject/数据汇总案例1.py

Process finished with exit code 0

 

posted @ 2024-01-08 12:14  往事已成昨天  阅读(16)  评论(0编辑  收藏  举报