简体   繁体   English

如何使用xlwt将python列表导出到excel文件中?

[英]How to export python list into excel file using xlwt?

Here I am trying to export python list to the excel file but it is not working correctly.在这里,我试图将 python 列表导出到 excel 文件,但它无法正常工作。

The list will be dynamic.该列表将是动态的。

response = HttpResponse(content_type='application/ms-excel')
response['Content-Disposition'] = 'attachment; filename="excle_file.xls"'

wb = xlwt.Workbook(encoding='utf-8')
ws = wb.add_sheet('datas', cell_overwrite_ok=True)

row_num = 0

font_style = xlwt.XFStyle()
font_style.font.bold = True

columns = ['col1', 'col2', 'col3', 'col4', 'col5']

for col_num in range(len(columns)):
    ws.write(row_num, col_num, columns[col_num], font_style)

font_style = xlwt.XFStyle()
rows = [20, Decimal('50000.00'), Decimal('10.00'), Decimal('40000.00'), Decimal('90000.00'), 21, Decimal('31000.00'), Decimal('2000.00'), Decimal('41000.00'), Decimal('74000.00')]

for i,e in enumerate(rows):
   ws.write(i,1, e)

wb.save(response)
return response

I want response like this.我想要这样的回应。

col1  col2   col3  col4  col5
20    50000   10   40000  90000
21    31000   2000 41000  74000

Current response当前响应

col1  col2   col3  col4  col5
      20    
      50000  
      10   
      40000  
      90000
      21    
      31000  
      ....

Also I want to increase the size of the column based on the text?另外我想根据文本增加列的大小? How it will be done ?将如何进行?

Per the docs https://xlwt.readthedocs.io/en/latest/api.html#xlwt.Worksheet.Worksheet ws.write takes (row,column,value).根据文档https://xlwt.readthedocs.io/en/latest/api.html#xlwt.Worksheet.Worksheet ws.write 需要(行、列、值)。 Compare what you get if you change:比较你改变后得到的结果:

ws.write(i,1, e)

to:到:

print(i,1, e)

and then how it changes if you put:然后如果你输入它会如何变化:

print(int(i/5),int(i)%5, e)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM