实列代码
:
import xlwt
import time
from io import BytesIO
from flask import make_response
def export_navi():
"""
导出excel数据
:param req:
:return:
"""
# 获取数据列表
devices = get_navi_page()
try:
# 创建Workbook,相当于创建Excel
book = xlwt.Workbook(encoding='utf-8')
sheet = book.add_sheet('Sheet1', cell_overwrite_ok=True)
row0 = ['所用卡ID', '定位时间', '经度', '维度', '航向', '航速']
# 设置列宽
sheet.col(0).width = 6000
sheet.col(1).width = 3000
sheet.col(2).width = 3000
sheet.col(3).width = 6000
sheet.col(4).width = 3000
sheet.col(5).width = 3000
sheet.col(6).width = 3000
sheet.col(7).width = 12000
# 写入excel表头
for i in range(0, len(row0)):
sheet.write_merge(0, 0, i, i, row0[i], set_style('Times New Roman', 220, True))
# 写入excel
for k, v in enumerate(devices, start=1):
sheet.write(k, 0, num)
sheet.write(k, 1, v.get("strftime"))
sheet.write(k, 2, v.get("longitude"))
sheet.write(k, 3, v.get("latitude"))
sheet.write(k, 4, v.get("direction"))
sheet.write(k, 5, v.get("speed"))
# 通过浏览器下载到客户端
output = BytesIO()
book.save(output)
output.seek(0)
response = make_response(output.getvalue())
output.close() # 关掉流
response.headers["Content-Disposition"] = "attachment; filename=navi"+time.strftime("%Y%m%d%H%M%S", time.localtime(time.time()))+".xlsx"
response.headers['Content-Type'] = 'application/x-xlsx'
return response
except BaseException as e:
response = {
'code': 1,
'msg': '下载失败'
}
return jsonify(response), 400
# 设置style格式
def set_style(name, height, bold=False):
"""
excel样式
:param name: 字体名
:param height: 调度
:param bold: 边框
:return:
"""
style = xlwt.XFStyle() # 初始化样式
font = xlwt.Font() # 为样式创建字体
font.name = name # 'Times New Roman'
font.bold = bold
font.color_index = 000
font.height = height
style.font = font
return style