Export Data from QuerySet as Excel File in Django

Let's say you have this function in your views.py:
def funtion_name(request):
    if request.method == "GET":
        get_id = request.user.id

        args = []
        kwargs = {
            'landproperty__sownerid__id': get_id,
            'geom__distance_lte': (pnt, D(km=kmdistance)),
            'narea__lte': getarea

        mm = YourModelHere.objects.filter(*args, **kwargs).values_list('fielname1', 'fielname2', 'fielname3','fielname4')
        request.session[0] = mm
        return HttpResponse(json.dumps(list(m)), content_type='application/json')

In order to get or pass the QuerySet from this function, you need to store it in a session as shown above.

Here's how to create an excel file:
def create_excel(request):
    book = xlwt.Workbook(encoding='utf8')
    sheet = book.add_sheet('untitled')

    default_style = xlwt.Style.default_style
    datetime_style = xlwt.easyxf(num_format_str='dd/mm/yyyy hh:mm')
    date_style = xlwt.easyxf(num_format_str='dd/mm/yyyy')

    headers = ['Table Header 1', 'Table Header 2', 'Table Header 3', 'Table Header 4']
    values_list = [headers] + list(request.session[0])

    for row, rowdata in enumerate(values_list):
        for col, val in enumerate(rowdata):
            if isinstance(val, datetime):
                style = datetime_style
            elif isinstance(val, date):
                style = date_style
                style = default_style
            sheet.write(row, col, val, style=style)

    response = HttpResponse(mimetype='application/vnd.ms-excel')
    response['Content-Disposition'] = 'attachment; filename=example.xls'
    return response

That's it! Just use the session variable from the previous function (funtion_name).

Popular posts from this blog

Set table width to 100% on PDF export in Datatables

Hot/Cute flat-chested Girls