mafu

统计数据的随笔写了两篇了,再来一篇,这是第三篇,前面第一篇是用xlwt写excel数据,第二篇是用xlwt写mysql数据。先贴要处理的数据截图:

再贴最终要求的统计格式截图:

第三贴代码:

 1 \'\'\'
 2     #利用openpyxl向excel模板写入数据
 3 \'\'\'
 4 #首先写本地excel的
 5 import xlwt
 6 import xlrd
 7 import openpyxl
 8 
 9 #提取数据
10 xlsx = xlrd.open_workbook("要处理的数据表路径/xxx.xlsx")
11 table = xlsx.sheet_by_index(0)
12 
13 #空列表,用以存储数据
14 all_data = []
15 
16 #循环,读取表格的每个单元格
17 for n in range(1, table.nrows):
18     date = table.cell_value(n, 0)
19     company = table.cell_value(n, 1)
20     province = table.cell_value(n, 2)
21     price = table.cell_value(n, 3)
22     weight = table.cell_value(n, 4)
23     #print(company,price,weight)
24     #开始提取我们需要的数据并存储到字典
25     data = {\'company\':company, \'price\':price, \'weight\':weight}
26     #print(data)
27     #将上面字典的每一项以追加的方式追加到空列表all_data
28     all_data.append(data)
29 
30 #print(all_data,type(all_data))
31 
32 #开始从字典里读取数据
33 a_weight = [] #存储张三粮配每车重量的列表
34 a_total_price = [] #存储张三粮配每车总价格的列表
35 b_weight = []
36 b_total_price = []
37 c_weight = []
38 c_total_price = []
39 d_weight = []
40 d_total_price = []
41 for i in all_data:
42     if i[\'company\'] == "张三粮配":
43         a_weight.append(i[\'weight\'])
44         a_total_price.append(i[\'weight\'] * i[\'price\'])
45     if i[\'company\'] == "李四粮食":
46         b_weight.append(i[\'weight\'])
47         b_total_price.append(i[\'weight\'] * i[\'price\'])
48     if i[\'company\'] == "王五小麦":
49         c_weight.append(i[\'weight\'])
50         c_total_price.append(i[\'weight\'] * i[\'price\'])
51     if i[\'company\'] == "赵六麦子专营":
52         d_weight.append(i[\'weight\'])
53         d_total_price.append(i[\'weight\'] * i[\'price\'])
54 #开始按表格要求的数据细化数据
55 #首先是张三的
56 a_che = len(a_weight)
57 a_dun = sum(a_weight)
58 a_sum_price = sum(a_total_price)
59 #李四
60 b_che = len(b_weight)
61 b_dun = sum(b_weight)
62 b_sum_price = sum(b_total_price)
63 #王五
64 c_che = len(c_weight)
65 c_dun = sum(c_weight)
66 c_sum_price = sum(c_total_price)
67 #赵六
68 d_che = len(d_weight)
69 d_dun = sum(d_weight)
70 d_sum_price = sum(d_total_price)
71 
72 #开始用openpyxl导入模板
73 tem_workbook = openpyxl.load_workbook("模板路径/统计表_openpyxl.xlsx") #这里注意是xlsx格式的
74 #获取工作表
75 tem_sheet = tem_workbook[\'Sheet1\'] #这里获取的工作表就是工作簿里的第一个表,表名看清楚
76 #开始写入数据
77 #写张三的,张三的在第三行第二到第四列
78 tem_sheet[\'B3\'] = a_che #在第三行第二列写入总车数
79 tem_sheet[\'C3\'] = a_dun #在第三行第三列写入总吨数
80 tem_sheet[\'D3\'] = a_sum_price #在第三行第四列写入总价格
81 #开始写李四的,李四在第四行,第二到第四列
82 tem_sheet[\'B4\'] = b_che
83 tem_sheet[\'C4\'] = b_dun
84 tem_sheet[\'D4\'] = b_sum_price
85 #开始写王五,王五的在第五行,第二到第四列
86 tem_sheet[\'B5\'] = c_che
87 tem_sheet[\'C5\'] = c_dun
88 tem_sheet[\'D5\'] = c_sum_price
89 #开始写赵六,赵六的在第五行,第二到第四列
90 tem_sheet[\'B6\'] = d_che
91 tem_sheet[\'C6\'] = d_dun
92 tem_sheet[\'D6\'] = d_sum_price
93 
94 #保存工作簿
95 tem_workbook.save(\'路径/2020-11-04-openpyxl-excel.xlsx\')

最后贴效果截图:

分类:

技术点:

相关文章: