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);
        })
posted @   金笛秀才  阅读(51)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示