flask+xlswriter+axios导出Excel
flask后端
starttime = request.json.get('starttime')
endtime = request.json.get('endtime')
# 根据时间查询数据库数据
data = Inspector.query.filter(Inspector.Inspect_time >= starttime, Inspector.Inspect_time <= endtime).all()
output = BytesIO()
workbook = xlsxwriter.Workbook(output)
worksheet = workbook.add_worksheet('sheet1')
format = workbook.add_format({'num_format': 'yyyy/m/d h:mm:ss'})
row = 0
col = 0
for i in data:
worksheet.write(row, col, i.Inspect_time)
worksheet.write(row, col+1, i.Machine_room)
worksheet.write(row, col+2, i.Cabinet_num)
worksheet.write(row, col+3, i.Asset_num_old)
worksheet.write(row, col+4, i.Asset_num_new)
worksheet.write(row, col+5, i.Error_info)
worksheet.write(row, col+6, i.Inspector)
row = row + 1
worksheet.set_column('A:A', 20, format)
workbook.close()
output.seek(0)
resp = make_response(output.getvalue())
resp.headers["Content-Disposition"] = "attachment; filename={}.xlsx".format('xjxt')
resp.headers['Content-Type'] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
return resp
JS代码,指定响应类型"responseType: "blob",否则打开Excel乱码
axios({
responseType: "blob" ,
method: 'post',
url: "/export",
data: {
starttime: t1,
endtime: t2
}
}).then(function(response){
const blob = new Blob([response.data]);
const url = window.URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = 'xjxt.xlsx'
a.click()
window.URL.revokeObjectURL(url)
}).catch(function (error){
console.log(error);
})
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律