Django查询的数据生成Excel并自动下载

本文介绍如何在Django中通过后端views.py处理前端请求,生成Excel文件并实现自动下载。前端按钮触发POST请求,后端接收到请求后进行相应处理。
摘要由CSDN通过智能技术生成

1.前端代码

前台页面,点击按钮,发送post请求。

<button id="export_data" type="button" class="btn btn-primary col-sm-5" style="margin-left: 10px" onclick="export_data()">导出excel</button>


function export_data(){
   
         var csrf=$('input[name="csrfmiddlewaretoken"]').val();
         const req = new XMLHttpRequest();
         //请求连接
         req.open('POST', '/product/export_data/', true);
         req.responseType = 'blob';
         req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); //设置请求头
         //请求参数
    	 req.send(
             'product_name='+$("#product_name").val()+
             '&&product_size='+$("#product_size").val()+
             '&&product_brand='+brand_selected+
             '&&product_model='+$("#product_model").val()+
             '&&csrfmiddlewaretoken='+csrf); //输入参数
         //返回结果
         req.onload = function() {
   
           debugger;
           const data = req.response;
           const blob = new Blob([data]);
           const blobUrl = window.URL.createObjectURL(blob);
           //模拟下载
           download(blobUrl) ;
         };
    }



function download(blobUrl) {
   
     debugger;
     //创建a标签,用于保存excel
     const a = document.createElement('a');
     a.style.display = 'none';
     
	 //下载文件的名称拼接
     var file_name_temp = "商品";
     if($("#product_name").
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

神奇洋葱头

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值