1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
| import openpyxl from openpyxl.chart import BarChart,Reference,BarChart3D
''' data = { 学院:{ 男:{男生人数,身高}, 女:{女生人数,身高 } } '''
print("正在打开文件") wb = openpyxl.load_workbook('test.xlsx') sheet = wb.active data = {} print("开始统计") for i in range(6,sheet.max_row): xueyuan = sheet['E'+str(i)].value sex = sheet['D'+str(i)].value hight = sheet['F'+str(i)].value weight = sheet['G'+str(i)].value data.setdefault(xueyuan,{}) data[xueyuan].setdefault(sex,{'num':0,'ah':0,'aw':0}) data[xueyuan][sex]['num'] += 1 data[xueyuan][sex]['ah'] +=float(hight) data[xueyuan][sex]['aw'] +=float(weight) print("稍等一下,马上出数据") for i in data.keys(): for j in data[i].keys(): data[i][j]['ah'] = data[i][j]['ah'] / data[i][j]['num'] data[i][j]['aw'] = data[i][j]['aw'] / data[i][j]['num'] print("即将将数据填入表格") lis_m = [] lis_w = [] list2 = [] list2.append('学院') list2.append('人数') list2.append('平均身高') list2.append('平均体重') lis_m.append(list2) lis_w.append(list2) for list1 in data.keys(): list3 = list(data[list1]['男'].values()) list3.insert(0,list1) lis_m.append(list3) list4=list(data[list1]['女'].values()) list4.insert(0, list1) lis_w.append(list4) print("将数据填成表格中") wb = openpyxl.Workbook() sheet = wb.create_sheet(index=0,title='test') sheet.append(['男生']) for i in lis_m: sheet.append(i) sheet.append(['女生']) for i in lis_w: sheet.append(i) print("表格生成完成,开始绘制图表。。。")
chart1 = BarChart()
chart1.type='col' chart1.style = 10 chart1.title = '男生' chart1.y_axis.title='身高体重' chart1.x_axis.title='学院'
cats = Reference(sheet,min_col=1,min_row=2,max_row=18) data2 = Reference(sheet,min_col=3,max_col=4,min_row=3,max_row=18) chart1.add_data(data=data2,titles_from_data=True) chart1.set_categories(cats) sheet.add_chart(chart1,'G1') chart2 = BarChart() chart2.type='col' chart2.style = 10 chart2.y_axis.title='身高体重' chart2.x_axis.title='学院' chart2.title = '女生' cats = Reference(sheet,min_col=1,min_row=21,max_row=36) data3 = Reference(sheet,min_col=3,max_col=4,min_row=21,max_row=36) chart2.add_data(data=data3,titles_from_data=True) chart2.set_categories(cats) sheet.add_chart(chart2,'G20') print("开始生成新文件。。。") wb.save('new.xlsx') print("完成!")
|