#!/usr/bin/python
#coding=utf-8
#导入模块
import xlsxwriter
#新建一个表文件
workbook = xlsxwriter.Workbook(‘sample.xlsx‘)
#新建一个表
worksheet = workbook.add_worksheet()
#新建一个图表对象
chart = workbook.add_chart({‘type‘:‘column‘})
#定义表头
#定义数据
title = [u‘业务名称‘,u‘星期一‘,u‘星期二‘,u‘星期三‘,u‘星期四‘,u‘星期五‘,u‘星期六‘,u‘星期日‘,u‘平均流量‘]
buname = [u‘业务官网‘,u‘新闻中心‘,u‘购物频道‘,u‘体育频道‘,u‘亲子频道‘]
data = [
[150,152,158,149,155,145,148],
[89,88,95,93,98,100,99],
[201,200,198,175,170,198,195],
[75,77,78,78,74,70,79],
[88,85,87,90,93,88,84],
]
#定义数据类型与格式
format=workbook.add_format()
format.set_border(1)
format_title=workbook.add_format()
format_title.set_border(1)
format_title.set_bg_color)(‘#cccccc‘)
format_title.set_align(‘centor‘)
format_title.set_blod()
format_ave=workbook.add_format()
format_ave.set_border(1)
format_ave.set_num_format(‘0.00‘)
#插入数据
worksheet.write_row(‘A1‘,title)
worksheet.write_column(‘A2‘,buname)
worksheet.write_row(‘B2‘,data[0])
worksheet.write_row(‘B3‘,data[1])
worksheet.write_row(‘B4‘,data[2])
worksheet.write_row(‘B5‘,data[3])
worksheet.write_row(‘B6‘,data[4])
#定义图表数据系列函数
def chart_series(cur_now):
worksheet.write_formula(‘I‘+cur_now, \
‘=AVERAGE(B‘+cur_now+‘:H‘+cur_now+‘)‘,‘format_ave‘)#计算平均值
chart.add_series({
‘categories‘:‘=Sheet1!$B$1:$H$1‘, #B1至H1元素作为x轴
‘values‘:‘=Sheet1!$B$‘+cur_now+‘:H‘+cur_now, #从B2-H2开始,每一行作为数据
‘line‘:{‘color‘:‘#cccccc‘}, #线条颜色
‘name‘:‘=Sheet1!$A$‘+cur_now, #引用A列作为数值类型
})
for row in range(2,7):
chart_series(str(row))
chart.set_size({‘width‘:577,‘height‘:277})
chart.set_title({‘name‘:u‘业务流量周报报表‘})
chart.set_y_axis({‘name‘:‘MB/s‘})
worksheet.insert_chart(‘A8‘,chart)
workbook.close()
excel表格效果: