在Django中使用Xlwt修改单元格的宽度

时间:2014-08-01 02:27:22

标签: python django excel

这是我目前在views.py中将代码模板信息下载到Excel文件中的代码:

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



    header_font = Font()

    # Header font preferences
    header_font.name = 'Times New Roman'
    header_font.height = 20 * 15
    header_font.bold = True

    # Header Cells style definition
    header_style = XFStyle()
    header_style.font = header_font 


    body_font = Font()

    # Body font preferences
    body_font.name = 'Arial'
    body_font.italic = True


    borders = Borders()
    borders.left = 1
    borders.right = 1
    borders.top = 1
    borders.bottom = 1
    header_style.borders = borders


    # body cell name style definition
    body_style = XFStyle()
    body_style.font = body_font 

    # 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): # [(0,'Header 1'), (1, 'Header 2'), (2,'Header 3'), (3,'Header 4')]
    sheet.write(0, hcol, hcol_data, header_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 column, key in enumerate(header, start=1):
        sheet.write(1, column, str(data[key]), body_style)


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

我想要做的是在没有任何成功的情况下,增加列的宽度以适应其中的信息。

任何帮助都将非常感激。感谢

1 个答案:

答案 0 :(得分:1)

header_style的内容是什么?尝试使用

...
content_format   = 'align: wrap on'
sheet.write(0, hcol, hcol_data, ezxf(content_format))
...

您可以通过以下方式定义单元格的宽度:

...
sheet.col(0).width = int(13*260)  
# 0 stands for col 0, 260 stands for 1mm so that this column's width is 13mm.
...

希望这有帮助。