0

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 ?

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

2 Comments

thanks +1 it solved one probelm but now the columns name col1, col2.. are missing
I've never used xlwt so guessing here, but change to int(i/5)+1 ? Before it started on row 0 which is where you've put the column names.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.