您好,登錄后才能下訂單哦!
怎么在python中利用xlsxwriter庫生成圖表?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:Eric.yue import xlsxwriter import random from datetime import date import collections def xlwt_chart(xl_obj,table): #生成柱狀圖 column_chart = xl_obj.add_chart({'type':'column'}) column_chart.add_series({ 'name':'=sheet1!$D$1', 'categories':'=sheet1!$D$2:$D$7', 'values':'=sheet1!$E$2:$E$7' }) table.insert_chart('G2',column_chart) #生成餅圖 column_chart2 = xl_obj.add_chart({'type':'pie'}) column_chart2.add_series({ 'name': '=sheet1!$D$1', 'categories':'=sheet1!$D$2:$D$7', 'values': '=sheet1!$E$2:$E$7' }) table.insert_chart('G20', column_chart2) def xlwt_run(): data_base = ['0-50','50-60','60-70','70-80','80-90','90-100'] #生成一個有序的字典 chart_dict = collections.OrderedDict.fromkeys(data_base,0) xl_obj = xlsxwriter.Workbook('chart.xlsx') table = xl_obj.add_worksheet('sheet1') table.write_string(0,0,u'姓名') table.write_string(0,1,u'成績') table.write_string(0,2,u'日期') table.merge_range('D1:E1', u'成績分布') table.set_column('C:E',15) #定義格式 date_format = xl_obj.add_format({'num_format':'yyyy-mm-dd'}) color_format = xl_obj.add_format({'color':'red'}) font_format = xl_obj.add_format({'font_color':'green','bold':True}) mm = 1 for i in xrange(1,40): name = 'name_%d' % i score = random.randint(30,100) if score <= 50: chart_dict['0-50'] += 1 elif score>50 and score<=60: chart_dict['50-60'] += 1 elif score>60 and score<=70: chart_dict['60-70'] += 1 elif score>70 and score<=80: chart_dict['70-80'] += 1 elif score>80 and score<=90: chart_dict['80-90'] += 1 else: chart_dict['90-100'] += 1 if score > 60: table.write_string(i, 0, name) table.write_number(i, 1, score) else: table.write_string(i, 0, name, color_format) table.write_number(i, 1, score, color_format) table.write_datetime(i, 2,date.today(), date_format) mm = mm + 1 #生成圖表數據 row = 1 for k,v in chart_dict.items(): table.write_string(row, 3, k, font_format) table.write_number(row, 4, v, font_format) row = row+1 xlwt_chart(xl_obj,table) #使用公式 table.write_formula(mm,1,'=AVERAGE(B2:B40)') #插入帶鏈接的圖片 table.insert_image('D20',r'/home/mywork/pythonchina/cto51_log/bd_logo12.png',{'url':'https://www.baidu.com'}) #關閉excel句柄 xl_obj.close() if __name__ == '__main__': xlwt_run()
看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注億速云行業資訊頻道,感謝您對億速云的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。