【问题标题】:Error while exporting excel file using Django and xlwt使用 Django 和 xlwt 导出 excel 文件时出错
【发布时间】:2022-01-23 05:16:28
【问题描述】:

使用django框架导出Excel文档的xlwt库,出现如下问题:

以 10 为基数的 int() 的无效文字:“产品名称”

我尝试在数据类型中使用不同的转换,但没有帮助。我想知道如何解决这个问题,谢谢你的建议。

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

【问题讨论】:

    标签: python-3.x django django-views xlwt


    【解决方案1】:

    通过在视图逻辑中添加一个遗漏点解决了这个问题

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

    【讨论】:

      猜你喜欢
      • 2021-11-14
      • 2018-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多