python xlsxwriter库生成图表的应用
xlsxwriter可能用过的人并不是很多,不过使用后就会感觉,他的功能让你叹服,除了可以按要求生成你所需要的excel外
还可以加上很形象的各种图,比如柱状图、饼图、折线图等。
请看本人生成的:
这里包含了数据公式的计算,插入图片的连接,生成的图表,当然如果你还需要其他的功能,可以继续参考库的文档
下面把源代码贴出来,希望对大家在工作遇到类似的情况,可以直接拿去用。不过转载的时候请注明出处。
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 # Author:Eric.yue 4 5 import xlsxwriter 6 import random 7 from datetime import date 8 import collections 9 10 def xlwt_chart(xl_obj,table): 11 12 #生成柱状图 13 column_chart = xl_obj.add_chart({'type':'column'}) 14 column_chart.add_series({ 15 'name':'=sheet1!$D$1', 16 'categories':'=sheet1!$D$2:$D$7', 17 'values':'=sheet1!$E$2:$E$7' 18 }) 19 table.insert_chart('G2',column_chart) 20 21 #生成饼图 22 column_chart2 = xl_obj.add_chart({'type':'pie'}) 23 column_chart2.add_series({ 24 'name': '=sheet1!$D$1', 25 'categories':'=sheet1!$D$2:$D$7', 26 'values': '=sheet1!$E$2:$E$7' 27 }) 28 table.insert_chart('G20', column_chart2) 29 30 31 def xlwt_run(): 32 data_base = ['0-50','50-60','60-70','70-80','80-90','90-100'] 33 34 #生成一个有序的字典 35 chart_dict = collections.OrderedDict.fromkeys(data_base,0) 36 37 xl_obj = xlsxwriter.Workbook('chart.xlsx') 38 table = xl_obj.add_worksheet('sheet1') 39 table.write_string(0,0,u'姓名') 40 table.write_string(0,1,u'成绩') 41 table.write_string(0,2,u'日期') 42 table.merge_range('D1:E1', u'成绩分布') 43 table.set_column('C:E',15) 44 45 #定义格式 46 date_format = xl_obj.add_format({'num_format':'yyyy-mm-dd'}) 47 color_format = xl_obj.add_format({'color':'red'}) 48 font_format = xl_obj.add_format({'font_color':'green','bold':True}) 49 50 mm = 1 51 for i in xrange(1,40): 52 name = 'name_%d' % i 53 score = random.randint(30,100) 54 if score <= 50: 55 chart_dict['0-50'] += 1 56 elif score>50 and score<=60: 57 chart_dict['50-60'] += 1 58 elif score>60 and score<=70: 59 chart_dict['60-70'] += 1 60 elif score>70 and score<=80: 61 chart_dict['70-80'] += 1 62 elif score>80 and score<=90: 63 chart_dict['80-90'] += 1 64 else: 65 chart_dict['90-100'] += 1 66 67 if score > 60: 68 table.write_string(i, 0, name) 69 table.write_number(i, 1, score) 70 else: 71 table.write_string(i, 0, name, color_format) 72 table.write_number(i, 1, score, color_format) 73 74 table.write_datetime(i, 2,date.today(), date_format) 75 mm = mm + 1 76 77 #生成图表数据 78 row = 1 79 for k,v in chart_dict.items(): 80 table.write_string(row, 3, k, font_format) 81 table.write_number(row, 4, v, font_format) 82 row = row+1 83 84 xlwt_chart(xl_obj,table) 85 #使用公式 86 table.write_formula(mm,1,'=AVERAGE(B2:B40)') 87 #插入带链接的图片 88 table.insert_image('D20',r'/home/mywork/pythonchina/cto51_log/bd_logo12.png',{'url':'https://www.baidu.com'}) 89 90 #关闭excel句柄 91 xl_obj.close() 92 93 if __name__ == '__main__': 94 xlwt_run()
没有使用类写,只是即兴而作。