python django 模板 页面导出excel

使用python django 模板 页面导出excel示例

view.py
from io import BytesIO
import xlwt

# 导出Excel文件
def export_excel(request):
    city = request.POST.get('city')
    list_obj = [{'place': u'广东', 'sum': '120', 'lng': 1, 'lat': 2}, {'place': u'深圳', 'sum': '220', 'lng': 3, 'lat': 4}]
    # 设置HTTPResponse的类型
    response = HttpResponse(content_type='application/vnd.ms-excel')
    response['Content-Disposition'] = 'attachment;filename='+city+'.xls'
    """导出excel表"""
    if list_obj:
        # 创建工作簿
        ws = xlwt.Workbook(encoding='utf-8')
        # 添加第一页数据表
        w = ws.add_sheet('sheet1') # 新建sheet(sheet的名称为"sheet1")
        # 写入表头
        w.write(0, 0, u'地名')
        w.write(0, 1, u'次数')
        w.write(0, 2, u'经度')
        w.write(0, 3, u'纬度')
        # 写入数据
        excel_row = 1

        for obj in list_obj:
            name = obj['place']
            sum = obj['sum']
            lng = obj['lng']
            lat = obj['lat']
            # 写入每一行对应的数据
            w.write(excel_row, 0, name)
            w.write(excel_row, 1, sum)
            w.write(excel_row, 2, lng)
            w.write(excel_row, 3, lat)
            excel_row += 1
        # 写出到IO
        output = BytesIO()
        ws.save(output)
        # 重新定位到开始
        output.seek(0)
        response.write(output.getvalue())
    return response

html

<button class="btn" onclick="export_tasks()" ondblclick="export_tasks()" ><i class="icon-download-alt"></i>导出</button>

<script type="text/javascript">
	function export_tasks()
	    {
	        var
	    csrf =$('input[name="csrfmiddlewaretoken"]').val();
	    const
	    req = new
	    XMLHttpRequest();
	    req.open('POST', '/export_excel/', true);
	    req.responseType = 'blob';
	    req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); // 设置请求头
	    req.send('city=' +$('#city').val() + "&&csrfmiddlewaretoken=" + csrf); // 输入参数
	    req.onload = function()
	    {
	        const data = req.response;
	    const a = document.createElement('a');
	    const blob = new Blob([data]);
	    const blobUrl = window.URL.createObjectURL(blob);
	    download(blobUrl);
	    };
	
	    }
	Date.prototype.format = function (fmt) {
	  var o = {
	    "M+": this.getMonth() + 1,                   //月份
	    "d+": this.getDate(),                        //日
	    "h+": this.getHours(),                       //小时
	    "m+": this.getMinutes(),                     //分
	    "s+": this.getSeconds(),                     //秒
	    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
	    "S": this.getMilliseconds()                  //毫秒
	  };
	
	  //  获取年份
	  // ①
	  if (/(y+)/i.test(fmt)) {
	    fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	  }
	
	  for (var k in o) {
	    // ②
	    if (new RegExp("(" + k + ")", "i").test(fmt)) {
	      fmt = fmt.replace(
	        RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
	    }
	  }
	  return fmt;
	}
	
	function download(blobUrl) {
	     const a = document.createElement('a');
	     a.style.display = 'none';     
	     var now = new Date();
	     var nowStr = now.format("YYYYMMDDhhmmss");
	     a.download = nowStr + '.xls';
	     a.href = blobUrl;
	     a.click();
	     document.body.removeChild(a);
	}
</script>
详细参考引用链接:https://www.jb51.net/article/182619.htm

​
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值