简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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