python - Django 中的 Xlwt 导出显示错误信息

标签 python django excel

我对此感到很难过。我在页面底部有一个按钮。该页面显示了账单的渲染信息,每个账单都是不同的,因此该信息一直在变化。该按钮位于此处,以便用户可以将账单下载为 Excel 文件。对于下载,我的views.py中有此代码:

def descarga(request,id_factura):
    fact = Factura.objects.get(pk= id_factura)
    book = xlwt.Workbook(encoding='utf8')
    sheet = book.add_sheet('report')   
    alignment = xlwt.Alignment()

    alignment.horz = xlwt.Alignment.HORZ_LEFT
    alignment.vert = xlwt.Alignment.VERT_TOP
    style = xlwt.XFStyle() # Create Style
    style.alignment = alignment # Add Alignment to Style

# write the header
    header = ['Cliente', 'Fecha de Factura', 'Tipo de Factura', 'Numero de Factura',      'Descripcion', 'Subtotal', 'IVA', 'Precio']
    for hcol, hcol_data in enumerate(header):
    sheet.write(0, hcol, hcol_data, style=xlwt.Style.default_style)

# write your data, you can also get it from your model
    data = {
        "Cliente": fact.nombre_cliente,
        "Fecha de Factura":fact.fecha_factura,
        "Tipo de Factura": fact.tipo_Factura,
        "Numero de Factura": fact.numero_De_Factura,
        "Descripcion": fact.descripcion,
        "Subtotal": fact.importe_sin_iva,
        "IVA": fact.iva,
        "Precio": fact.importe_Total,
           }

    for row, row_data in enumerate(data, start=1): # start from row no.1
        for col, col_data in enumerate(row_data):
             sheet.write(row, col, col_data)


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

我得到的是正确的标题,但是我试图通过数据字典获取的信息没有显示,而是我得到的标题名称按列逐个字母分隔,如下所示:

N   u   m   e   r   o       d   e       F   a   c   t   u   r   a

其中每个字母都是 Excel 文件中的一列

那么,我该如何解决这个问题并显示正确的信息而不是这个。 任何帮助将不胜感激。谢谢

最佳答案

错误在这里:

for row, row_data in enumerate(data, start=1): 

其中您的行是 1,2,3,4...,您的 row_data 是字符串数据的键,然后第二个循环将在该字符串(键)上进行

for col, col_data in enumerate('Numero de Factura'):

也许尝试替换:

for row, row_data in enumerate(data, start=1): # start from row no.1
        for col, col_data in enumerate(row_data):
             sheet.write(row, col, col_data)

通过这个:

for column, key in enumerate(header, start=1):
    sheet.write(1, column, data[key])

关于python - Django 中的 Xlwt 导出显示错误信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25065588/

相关文章:

Django南: models are shown as not synced even if they are (or should be)

python - Django 和 Postgresql 的重复条目

vba - 如何从 Excel (VBA) 中的代码设置下拉选择

vba - 设置一个 VBA 宏,它将为我的主工作表中的每一行信息创建一个新工作表并以某种格式布局?

python - data.norm() < 1000 在 PyTorch 中做什么?

Python 素数集

python - 比 loc 更有效的清理数据帧的方法

python - 导入错误 : No module named django. core.wsgi

python - 如何按升序对这个 float 数值列表进行排序?

excel - 如何粘贴值并保持源格式?