尝试在Django中将数据从数据库导出到excel

问题描述

views.py

def export(request):
    print('start')
    ourid = request.POST.getlist("terid")
    queryset = Case_Info.objects.filter(id__in=list(map(int,ourid)))
    Case_Detail = Case_Info_Resource()
    print(ourid)
    dataset = Case_Detail.export(queryset)  # error in this line
    response = HttpResponse(
        dataset.xls,content_type='application/vnd.ms-excel')
    response['Content-disposition'] = 'attachment; filename="persons.xls"'
    print('end')
    return response

Ajax脚本

$(document).ready(function () {
    $('#Download').click(function () {
        console.log("clicked!")
        var list = [];
        $("input:checkBox[name='checkBox']:checked").each(function () {
            list.push($(this).val());
        });
        $('#Download').attr('disabled','disabled');
        $.ajax({
            url: '/Account_Manager/Download/',type: 'POST',data: {
                'terid': list,'csrfmiddlewaretoken': '{{csrf_token}}',},timeout: 30000,Traditional: true,dataType: 'text',success: function () {
                alert("The best cricketers are: " + list.join(","));
                $('#Download').removeAttr('disabled');
            }
        });
    });
});

我想做的是从前端向后端传递几个ID,然后从数据库中相应地导出数据。一切正常,直到下面这一行。

dataset = Case_Detail.export(queryset)

在此行之后,它再次到达函数的开头,从而导致空白列表,从而导致一个空的excel文件

Output

解决方法

所以,终于,我实现了我想要的。

我想将选定的ID(多个ID)从前端传递到后端,然后相应地从数据库中获取数据。之后,我想将数据导出为ex​​cel或CSV格式。

Ajax:

<script>

    $(document).ready(function (e) {
        $('#Download').click(function (e) {
            e.preventDefault()
            console.log("clicked!")
            var list = [];
            $("input:checkbox[name='checkbox']:checked").each(function () {
                list.push($(this).val());
            });
            $.ajax({
                url: '/Account_Manager/Download/',type: 'POST',data: {
                    'terid': list,'csrfmiddlewaretoken': '{{csrf_token}}',},traditional: true,dataType: 'text',success: function (response,status,xhr) {
                    var filename = "persons.csv";
                    var disposition = xhr.getResponseHeader('Content-Disposition');
                    if (disposition && disposition.indexOf('attachment') !== -1) {
                        var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
                        var matches = filenameRegex.exec(disposition);
                        if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g,'');
                    }

                    var type = xhr.getResponseHeader('Content-Type');
                    var blob = new Blob([response],{type: type});

                    if (typeof window.navigator.msSaveBlob !== 'undefined') {
                        // IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed."
                        window.navigator.msSaveBlob(blob,filename);
                    } else {
                        var URL = window.URL || window.webkitURL;
                        var downloadUrl = URL.createObjectURL(blob);

                        if (filename) {
                            // use HTML5 a[download] attribute to specify filename
                            var a = document.createElement("a");
                            // safari doesn't support this yet
                            if (typeof a.download === 'undefined') {
                                window.location.href = downloadUrl;
                            } else {
                                a.href = downloadUrl;
                                a.download = filename;
                                document.body.appendChild(a);
                                a.click();
                            }
                        } else {
                            window.location.href = downloadUrl;
                        }

                        setTimeout(function () {
                            URL.revokeObjectURL(downloadUrl);
                        },100); // cleanup
                    }
                }
            });

        });
    });
</script>

Person.csv是我通过views.py传递的文件

View.py

def export(request):
    ourid = request.POST.getlist("terid")
    queryset = Case_Info.objects.filter(id__in=list(map(int,ourid)))
    dataset = Case_Info_Resource().export(queryset)
    response = HttpResponse(dataset.csv,content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="persons.csv"'
    return response

如果您的数据集重播了一个空列表,请检查“开发人员”选项卡的控制台中文档中包含的js文件中的错误,并确保您在同一文件中没有两次包含任何js文件。

感谢所有帮助过我的人