Reputation: 289
This is the code that i have right now in my views.py to download information of a template into an excel file:
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
What i´m trying to do, without any success, is to increase the width of the columns to fit the information in them.
Any help will be really appreciated. Thanks
Upvotes: 2
Views: 4311
Reputation: 4912
What's the content of header_style? Try to use
...
content_format = 'align: wrap on'
sheet.write(0, hcol, hcol_data, ezxf(content_format))
...
And you can define width of your cell at the beginning by:
...
sheet.col(0).width = int(13*260)
# 0 stands for col 0, 260 stands for 1mm so that this column's width is 13mm.
...
Hope this helps.
Upvotes: 4