【问题标题】:Trying to export data from database to excel in django尝试将数据从数据库导出到 django 中的 excel
【发布时间】:2020-08-11 10:22:40
【问题描述】:

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 文件

【问题讨论】:

  • 因此导出函数似乎被调用了两次(两个“开始”输出)。什么叫它两次?您可以删除 ajax 并自行调用视图吗?在第二次调用中,没有“ourid”值。这是因为它被称为 GET 而不是 POST?
  • @MatthewHegarty 你第二次写它被称为 GET。感谢您添加。查看自己的工作正常。但我需要 ajax 来传递选定的复选框。这样我就可以只下载选定的数据。
  • 它应该可以正常工作,您只需要弄清楚为什么 Ajax 会进行两次调用。会不会是双击?可以在某处刷新页面吗?
  • @MatthewHegarty,thanx 伙计,我的 jquery 没有正确包含。所以现在它只调用一次。但现在它没有下载 excel。
  • @MatthewHegarty 我可以在开发人员选项卡中看到响应数据,但文件没有被下载。

标签: jquery django ajax django-import-export jsajaxfileuploader


【解决方案1】:

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

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

阿贾克斯:

<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 传递的文件

查看.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 文件。

感谢所有帮助过我的人

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-22
    • 2016-08-08
    • 2017-02-09
    • 1970-01-01
    相关资源
    最近更新 更多