Error while exporting excel file using Django and xlwt

302 Views Asked by At

Working with the xlwt library for exporting Excel docs using the Django framework, the following problem appeared:

invalid literal for int() with base 10: 'Name of product'

I tried to use different conversions in data types, but it didn't help. I would like to know how to solve this problem, thank you for any advice.

models.py:

class Product(models.Model):
    name = models.CharField(max_length=100, null=True)
    quantity = models.PositiveIntegerField(null=True)
    category = models.CharField(max_length=50, choices=CATEGORY, null=True)

    def __str__(self):
        return f'{self.name}'

views.py:

def export_excel(request):
    response=HttpResponse(content_type='application/ms-excel')
    response['Content-Disposition'] = 'attachment: filename=Expenses' + \
        str(datetime.datetime.now())+'.xls'
    wb = xlwt.Workbook(encoding='utf-8')
    ws = wb.add_sheet('Expenses')
    row_num = 0
    font_style = xlwt.XFStyle()
    font_style.font.bold = True

    columns= ['Name of product', 'Category', 'Quantity']

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

    font_style = xlwt.XFStyle()

    rows = Product.objects.filter(owner=request.user).values_list(
        'name', 'quantity', 'category')

    for row in rows:
        row_num += 1

        for col_num in range(len(row)):
            ws.write(row_num, str(row[col_num]), font_style)
    wb.save(response)

    return response
1

There are 1 best solutions below

0
existentia On

Solved this issue, by adding one missed point in views logic

ws.write(row_num, col_num, columns[col_num], font_style)