前端代码

$("#id_pullout").click(function () {
//发送ajax请求
$.ajax({
url: '/pullout/', //请求的url
method: "post", //默认get
xhrFields: {
responseType: "arraybuffer",
},
    // 这个选项必须得有,要不文件打不开
data: {'csrfmiddlewaretoken': '{{ csrf_token }}'},
success: function (response) {
        //data接收响应体,必须要有
let blob = new Blob([response], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        //这里。必须得指定格式,每个格式的文件都不一样
});
let link = document.createElement("a");
link.href = window.URL.createObjectURL(blob);
<!--link.download = fileName;-->
link.download = '导出数据.xlsx';
link.click();
window.URL.revokeObjectURL(link.href);
}
})
})

后端
def export_datas(request):
try:
    //  这里重新封装了reponse,
response = HttpResponse()
response['Content-Type'] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
     
# todo fileName
file_time = time.strftime('%Y-%m-%d %X')
response['fileName'] = file_time+'/'+request.user.username+'.xlsx'
response['Content-Disposition'] = 'attachment;filename="{}.xlsx"'.format(file_time)
response['Accept-Encoding'] = 'gzip, deflate, br'
# print(response.get('fileName'))
outdata=BytesIO()
    // 使用IO操作,把二进制数据存起来
with open('导出文件.xlsx','rb') as f:
outdata.write(f.read())
response.write(outdata.getvalue())
     //这个啥操作没看懂说实话
return response
except Exception as e:
print([e])
return e
这个是魔改了其他大神的东西,有的地方不是很明白,但是起码能用在自己的项目上了
原文链接如下,
https://www.cnblogs.com/jun-zhou/p/16219664.html
posted on 2022-11-22 17:33  阿勒泰的鱼  阅读(202)  评论(0)    收藏  举报