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

这是我现在在我的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 

我试图做的,没有任何成功,是增加列的宽度,以适应其中的信息。

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

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. ... 

希望这可以帮助。