def get_excel(data, field, file, riqi):
# 将数据和字段名写入excel的函数
# 新建一个工作薄对象
new = openpyxl.Workbook()
# 激活一个新的sheet
sheet = new.active
# 给sheet命名
sheet.title = u"测试数据" + riqi
font=Font(name='微软雅黑',size=9,bold=False,italic=False,vertAlign=None,underline=None,strike=False,color='FF000000')
font1 = Font(name='微软雅黑', size=9, bold=True, italic=False, vertAlign=None, underline=None, strike=False,
color='FFFFFFFF')
border=Border(left=Side(style='thin',color='FF000000'),
right=Side(style='thin',color='FF000000'),
top=Side(style='thin',color='FF000000'),
bottom=Side(style='thin', color='FF000000'))
fill = PatternFill(fill_type='solid',
start_color='336666')
# 将字段名称循环写入excel第一行,因为字段格式列表里包含列表,每个列表的第一元素才是字段名称
for col in range(len(field)):
# row代表行数,column代表列数,value代表单元格输入的值,行数和列数都是从1开始,这点于python不同要注意
_ = sheet.cell(row=1, column=col + 1, value=u'%s' % field[col][0])
sheet.cell(row=1, column=col + 1).font = font1
sheet.cell(row=1, column=col + 1).fill = fill
sheet.cell(row=1, column=col + 1).border = border
# 将数据循环写入excel的每个单元格中
for row in range(len(data)):
for col in range(len(field)):
# 因为第一行写了字段名称,所以要从第二行开始写入
_ = sheet.cell(row=row + 2, column=col + 1, value=data[row][col])
sheet.cell(row=row+2, column=col + 1).font = font
sheet.cell(row=row+2, column=col + 1).border = border
sheet.append(
['合计', '=sum(b2:b' + str(row + 2) + ')', '=sum(c2:c' + str(row + 2) + ')', '=sum(d2:d' + str(row + 2) + ')',
'=sum(e2:e' + str(row + 2) + ')'])
for col in range(len(field)):
# row代表行数,column代表列数,value代表单元格输入的值,行数和列数都是从1开始,这点于python不同要注意
sheet.cell(row=row+3, column=col + 1).font = font1
sheet.cell(row=row+3, column=col + 1).fill = fill
sheet.cell(row=row+3, column=col + 1).border = border
values = Reference(sheet, min_col=2, min_row=1, max_col=4, max_row=row + 2)
titles = Reference(sheet, min_col=1, min_row=2, max_row=row + 2)
chart = BarChart()
chart.title = sheet.title
chart.hight=20
chart.width=25
chart.add_data(values, titles_from_data=True)
chart.set_categories(titles)
sheet.add_chart(chart, 'A' + str(row + 6), )
# 将生成的excel保存,这步是必不可少的
newworkbook = new.save(file)
# 返回生成的excel
return newworkbook