[Answer]-Django download query as csv

1👍

Django has its own csv library. If that doesn’t suit what you’re looking for maybe check out django-data-export. Good luck and hope this helps!

👤Greg

0👍

I use xlwt to export models to excel, I think this code can FYI

from xlwt import Workbook
def get(self, request, *args, **kwargs):
    book = Workbook(encoding='utf-8')
    // fill book with your data here...
    response = HttpResponse(content_type='application/ms-excel')
    book.save(response)
    response['Content-Disposition'] = 'attachment; filename="%s"' % self.excel_file_name.encode("utf-8")
    response['Cache-Control'] = 'no-cache'
    return response

0👍

I found the following code snippet from the django docs helpful:

import csv
from django.http import HttpResponse

def some_view(request):
    # Create the HttpResponse object with the appropriate CSV header.
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'

    writer = csv.writer(response)
    writer.writerow(['First row', 'Foo', 'Bar', 'Baz'])
    writer.writerow(['Second row', 'A', 'B', 'C', '"Testing"', "Here's a quote"])

    return response

Leave a comment