使用HttpResponse

时间:2017-10-01 12:55:21

标签: python django

下午好。我需要以excel格式从数据库下载数据。下面,当我尝试通过firefox下载文件时,我的代码及其工作正确,但使用chrome这个视图返回存档与一些openpyxl文件。 Openpyxl - 这个库我用来在excel_download()函数中填充数据库中的excel表。你能帮我解决一下吗?

def excel_download_view(request, **kwargs):
    if 'sorting_argument' in kwargs:
        queryset = Lot.objects.filter(
            Q(bank__slug__iexact=kwargs['sorting_argument']) |
            Q(auction_date__iexact=kwargs['sorting_argument']) |
            Q(which_time_auction__iexact=kwargs['sorting_argument']) |
            Q(fgvfo_number__iexact=kwargs['sorting_argument']) |
            Q(prozorro_number__iexact=kwargs['sorting_argument']) |
            Q(decision_number__iexact=kwargs['sorting_argument'])
        )
    else:
        queryset = Lot.objects.all()

    excel_download(queryset)

    data = None

    with open('media/excel/lots.xlsx', 'rb') as f:
        data = f.read()

    return HttpResponse(data, content_type='application/vnd.ms-excel')

1 个答案:

答案 0 :(得分:1)

response-as-a-file-attachment尝试:

response = HttpResponse(data, content_type='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename="lots.xlsx"'
return response