前言
本文使用axios和openpyxl,想要了解这两个的同学链接如下: openpyxl:https://blog.csdn.net/i_coffer/article/details/112134491 通过python来读取数据库生成excel文件 axios:https://blog.csdn.net/gao_xu_520/article/details/79726298 前端发送请求的一种方式
前端代码
responseType: 'blob’这步十分关键
<template>
<!-- 通过按钮的方式来下载文件做测试-->
<el-button plain @click="getEventDay()">朴素按钮</el-button>
</template>
<script>
import axios from 'axios'
export default {
data () {
return {
}
},
methods: {
async getEventDay () {
axios({
method: 'post',
url: 'http://127.0.0.1:8000/api/event_day/',
responseType: 'blob'
}).then(res => {
var disposition = res.headers['content-disposition']
var fileName = decodeURI(disposition.substring(disposition.indexOf('filename=') + 9, disposition.length))
const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
const link = document.createElement('a')
link.href = window.URL.createObjectURL(blob)
link.download = fileName
link.click()
link.remove()
}).catch(err => {
var enc = new TextDecoder('utf-8')
var res = JSON.parse(enc.decode(new Uint8Array(err.data)))
console.log(res)
})
}
}
}
</script>
<style scoped>
</style>
后端代码
from openpyxl import Workbook
def event_day(request):
# django里面的特定调用数据库的方法
report = models.ReportForm.objects.all()
#创建对象
wb = Workbook()
#起文件名字
dest_filename = '日报'
#创建sheet
ws1 = wb.active
ws1.title = "dayilyCount"
#给excel的单元格填写内容
ws1.cell(1, 1, 'id')
ws1.cell(1, 2, '1234')
ws1.cell(1, 3, '事件类型')
ws1.cell(1, 4, '备注')
row = 2
col = 1
for rep in report:
ws1.cell(row, col, rep.id)
ws1.cell(row, col + 1, rep.time)
ws1.cell(row, col + 2, rep.type)
ws1.cell(row, col + 3, rep.payload)
row = row + 1
#返回内容
response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', charset='utf-8')
response['Content-Disposition'] = 'attachment; filename={0}.xlsx'.format(quote(str(dest_filename)))
response['Access-Control-Expose-Headers'] = 'Content-Disposition'
wb.save(response)
return response
问题一
解决方案是因为之前测试的时候使用了mockjs,将mock模块删除就好了
问题二
无法传输文件名 解决方案:后端添加 response[‘Access-Control-Expose-Headers’] = 'Content-Disposition’ 前端设置 responseType: 'blob’
|