Django 实现excel导出和下载

 

后台代码:


@csrf_exempt
def Export_excel(request):  # 生成EXCEL表格
    if request.method == 'POST':
        try:
            now = datetime.datetime.now()
            expid = request.POST.get('expid')
            print('request.get', expid)
            # print(type(numerofdata))
            registernames =json.loads(request.POST.get("namechoose"))

            print("registernames:",registernames)
            registerids=[]
            filename='IDs'
            for name in registernames:
                temp_registerid=VInfoRegister.objects.get(v_name=name).register_id
                temp_subsys = VInfoRegister.objects.get(v_name=name).subsys_id
                filename = filename +str(temp_subsys)+str(temp_registerid)
                registerids.append(temp_registerid)
                print(registerids)
            file_path = os.path.join(r'static/excel/', '%s.xls' % (now.strftime("%Y-%m-%d-%H-%M-%S")+filename))
            #

            print('we are at data download')
            print(request.content_type)
            # list_obj=[]
            for registerid in registerids:
                list_obj=VDataMonitor.objects.filter(exp_id=expid,register_id=registerid)
            # list_obj =list_obj [0:int(numerofdata)]
            # print(list_obj[0].register_id)


            if list_obj:
                # 创建工作薄
                ws = Workbook(encoding='utf-8')
                w = ws.add_sheet(u"数据报表第一页")
                w.write(0, 0, "subsys_id")
                w.write(0, 1, u"register_id")
                w.write(0, 2, u"exp_id")
                w.write(0, 3, u"v_data")
                w.write(0, 4, u"v_data_time")

                # 写入数据
                excel_row = 1
                for obj in list_obj:
                    w.write(excel_row, 0, obj.subsys_id)
                    w.write(excel_row, 1, obj.register_id)
                    w.write(excel_row, 2, obj.exp_id)
                    w.write(excel_row, 3, obj.v_data)
                    w.write(excel_row, 4, obj.v_data_time.strftime("%Y-%m-%d %H:%M:%S.%f"))
                    excel_row += 1
                # 检测文件是够存在
                # 方框中代码是保存本地文件使用,如不需要请删除该代码
                ###########################
                # exist_file = file_path+'test.xls'
                # if exist_file:
                #     os.remove(r"test.xls")
                ws.save(file_path)
                print('file_path',file_path)
                print('we have saved the file ')
            return JsonResponse({'code': 0, 'data': file_path})  # 将路径返回到前台
        except Exception as e:
            print(e)
            return JsonResponse({'code': 1, 'data': '导出表格失败!'})
    elif request.method == 'GET':
        print('we are at get method part')
        excel_download(request)


def excel_download(request):
    try:
        filename = request.GET.get('data',None)
        def file_iterator(file_name):
            with open(file_name, 'rb')as f:
                while True:
                    c = f.read(512)
                    if c:
                        yield c
                    else:
                        break
        response = StreamingHttpResponse(file_iterator(filename))
        response['Content-Type'] = 'application/octet-stream'
        response['Content-Disposition'] = "attachment;filename={0}".format(filename.split('/')[2])#这里改成自己需要的文件名
        return response
    except Exception as e:
        print (e)

urls:

path('dataview/excel_export/', views.Export_excel, name='excel_export'),
path('dataview/excel_download/', views.excel_download, name='excel_download'),

 

前台代码:


$('#datadownload_btn').click(function(){
    console.log('we are at download fuicntion ')
    var expid= $("#expid").val();
    var timechoose=$("#v_timechoose").val();
    var multinamechoose=$("#download_v_namechoose").val();
    console.log(multinamechoose);
    var data1={'expid':expid,'timechoose':timechoose,'namechoose':JSON.stringify(multinamechoose)};
    console.log(data1);
    // $.ajaxSetup({
    //     headers: { "X-CSRFToken": getCookie("csrftoken") }
    // });

    $.ajax({
        type:"POST",
        data: data1,
        url: "/dataview/excel_export/", //后台处理函数的url
        dataType: "json",
        success: function(arg){
                console.log('后台反应会的数据');
                console.log(arg.data);
                 if (arg.code===0){
                    window.location.href='/dataview/excel_download?data='+arg.data+'';
                }else{
                    alert(arg.data)
                }

        },
        error: function(){
            alert("false");
        }
    });
    return false;
});

 

 

 

 

特别注意:关文件名称的问题,

如果文件名称中采用中文就会出现下载的时候浏览器没有办法识别文件的类型,因此,你在保证自己下载的文件的名称的时候应当采用的是英文+数字的组成格式,不要采用中文/。

会变成下面的样子“

Django 实现excel导出和下载_第1张图片

 

 

持续更新中

项目github:https://github.com/Scottars/nis_website

 

你可能感兴趣的:(Python,djgango)