使用xlwt导出excel与python并调整宽度

我已经使用xlwt导出了我的列表:

response = HttpResponse(mimetype="application/ms-excel") response['Content-Disposition'] = 'attachment; filename=Countries.xls' wb = xlwt.Workbook() ws1 = wb.add_sheet('Countries') ws1.write(0, 0, 'Country Name') ws1.write(0, 1, 'Country ID') countries = Country.objects.all() index = 1 for country in countries: ws1.write(index, 0, country.country_name) ws1.write(index, 1, country.country_id) index +=1 

它会生成一个带有国家/地区列表的Excel文件,但问题在于表单的列未被调整为生成的数据。 有没有解决scheme来调整这些列?

没有内置的方法来调整列宽使用xlwt的数据。

这个问题已经在这里提出了,所以我只想提到你:

  • Python xlwt – 访问现有的单元格内容,自动调整列宽
  • Python XLWT调整列宽
  • 约翰·Machin的主题的答案
    • 放大xlwt +自动调整列的宽度
    • 自动调整栏格式

基本上,您应该跟踪每列中的最大数据长度,并根据字体大小和样式手动调整列宽。

希望有所帮助。