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 @ 2023-03-22 16:08  金笛秀才  阅读(65)  评论(0)    收藏  举报