Python利用openpyxl帶格式統計數據(1)- 處理excel數據


統計數據的隨筆寫了兩篇了,再來一篇,這是第三篇,前面第一篇是用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')

最后貼效果截圖:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM