django 前端使用ajax发送查询条件,后端查询并生成excel实现下载功能

最近在做一个功能,需要使用ajax实现条件组合查询,将查询结果内容生成excel下载。
经过查阅和尝试,ajax不能接收处理文件流,无法实现功能,最终解决思路为“ajax传送查询条件到后端-后端查询-后台将结果保存到服务器指定临时目录-将存放路径及文件名返回前端ajax-前端下载”,每次写文件时自动清理临时文件存放目录,释放存储空间。
编程纯属个人爱好,以实现功能为主,请忽略代码质量,部分代码如下:
前端原生ajax传送条件到后台并接收后端返回的文件存放路径并下载:

function submitsearchconditionstoexcel() {
        form = document.getElementById('activeddatasearchconditionsform'); /* 获得表单对象,内容为拼接的查询条件 */
        fd = new FormData(form);  /* 根据表单对象,创建formdata对象,其包含用户提交的数据 */
        var xhr = new XMLHttpRequest();
        xhr.open('post', '/techapp/doquerysearchtoexcel/');/* 发送给后端 */
        xhr.send(fd);  /* 通过send函数将数据发给服务器 */
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                if (xhr.status == 200 || xhr.status == 304) {
                   var ret = eval("(" + xhr.responseText + ")");
                   var filelocal=ret.filename;/* 获取文件在服务器存放路径 */
                   window.location.href = filelocal;/*下载*/
                }
            }
        }
    }

自动删除服务器临时目录下的xls文件

def deltempfiles(path):
        # 先导入所需的包
    import os
    # 指定路径
    for root, dirs, files in os.walk(path):
        for name in files:
            if name.endswith(".xls"):  # 填写规则
                os.remove(os.path.join(root, name))
                print("Delete File: " + os.path.join(root, name))

后端查询及生成写入excel:

def doquerysearchdatatoexcel(request):  #将查询结果导出到excel
    result = well_activedata.objects.filter(wa_isdeleted=0)
   
    if request.POST.get("select_wellorrigname") != '':
        if request.POST.get("select_wellorrigname") == 'like':
            result = result & well_activedata.objects.filter(
                Q(wa_wellname__icontains=request.POST.get("searchform_wellorrigname")) | Q(
                    wa_rig__icontains=request.POST.get("searchform_wellorrigname")))
         
        else:
            result = result & well_activedata.objects.filter(
                Q(wa_wellname=request.POST.get("searchform_wellorrigname")) | Q(
                    wa_rig=request.POST.get("searchform_wellorrigname")))
            
    
    # 以上为拼接查询条件并逐条筛选,根据自己需要编写
    # 设置HTTPResponse的类型
    response = HttpResponse(content_type='application/vnd.ms-excel')
    response['Content-Disposition'] = 'attachment;filename=searchresult.xls'
    # 创建一个文件对象
    wb = xlwt.Workbook(encoding='utf8')
    # 创建一个sheet对象
    sheet = wb.add_sheet('order-sheet')
    # 设置文件头的样式,这个不是必须的可以根据自己的需求进行更改
    style_heading = xlwt.easyxf("""
            font:
                name Arial,
                colour_index black,
                bold on,
                height 0xA0;
            align:
                wrap off,
                vert center,
                horiz center;
            pattern:
                pattern solid,
                fore-colour 22;
            borders:
                left THIN,
                right THIN,
                top THIN,
                bottom THIN;
            """)

    # 写入文件标题(根据自己数据库情况)
    sheet.write(0,0,'平台',style_heading)
    sheet.write(0,1,'井号',style_heading)
    sheet.write(0,2,'区域',style_heading)
    
    sheet.write(1,0,'',style_heading)
    sheet.write(1,1,'',style_heading)
    sheet.write(1,2,'',style_heading)
    
    # 写入数据
    data_row = 2
    # UserTable.objects.all()这个是查询条件,可以根据自己的实际需求做调整.
    # for i in well_activedata.objects.all():
    for i in result:
        # print('****')
        # print(data_row)
        # 格式化datetime
        # pri_time = i.pri_date.strftime('%Y-%m-%d')
        # oper_time = i.operating_time.strftime('%Y-%m-%d')
        sheet.write(data_row,0,i.wa_rig)
        sheet.write(data_row,1,i.wa_wellname)
        sheet.write(data_row,2,i.wa_local)
       
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
     # 删除储存路径下的文件
    deltempfiles(BASE_DIR + "/media/tempfile/")
    path = BASE_DIR + "/media/tempfile/" + 'New-' + timestr + '.xls'  # 储存路径
    wb.save(path)# 将文件写入储存路径
    content = {       
        'filename':"/media/tempfile/" + 'New-' + timestr + '.xls',
    } # 将文件储存路径返回前端
    return JsonResponse(content)

前端html:

<button  onclick="submitsearchconditionstoexcel()" class="btn btn-success" type="button" >结果导出excel</button>
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值