Home > OS >  Django Excel Export (using xlwt)
Django Excel Export (using xlwt)

Time:09-22

I'm trying to export data tied to an id from a view, to an excel file, this is the code:

from django.shortcuts import render
from clientesapp.models import Cliente, Orden
from django.http import HttpResponse
import xlwt

def excel_create(request, id):
    
    response = HttpResponse(content_type='application/ms-excel')
    response['Content-Disposition'] = 'attachment; filename="recibo.xls"'

    wb = xlwt.Workbook(encoding='utf-8')
    ws = wb.add_sheet('recibo')

    row_num = 0
    font_style = xlwt.XFStyle()
    font_style.font.bold=True

    columns = ['Orden', 'Cliente', 'Entrada', 'Instrumento', 'Marca',]

    for col_num in range(len(columns)):
        ws.write(row_num, col_num, columns[col_num], font_style)

    font_style = xlwt.XFStyle()

    rows = Orden.objects.get(id=id)
    rows.values_list('num_orden', 'client', 'fechain', 'instrumento', 'marca')
    
    for row in rows:
        row_num  =1
        for col_num in range(len(row)):
            ws.write(row_num, col_num, row[col_num], font_style)

    wb.save(response)

    return response

I want to export to excel this table, that also shows the id i need to get the data: Table with id

But this code shows me the error "Orden object have no attribute values_list". How can i solve this problem?

CodePudding user response:

According to QuerySet API you have to call it like this:

rows = Orden.objects.values_list('num_orden', 'client', 'fechain', 'instrumento', 'marca', flat=True).get(pk=id)
  • Related