djangopython-3.xdjango-viewsxlwtdjango-excel

How to i transpose rows and columns in Django excel export file


Here is the sample code which i am struggling to transpose the data

def export_users_xls(request):
   response = HttpResponse(content_type='application/ms-excel')
   response['Content-Disposition'] = 'attachment; filename="users.xls"'

  wb = xlwt.Workbook(encoding='utf-8')
  ws = wb.add_sheet('Users')

   # Sheet header, first row
   row_num = 0

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

   columns = ['Username', 'First name', 'Last name', 'Email address', ]

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

   # Sheet body, remaining rows
   font_style = xlwt.XFStyle()

    rows = User.objects.all().values_list('username', 'first_name', 'last_name', 'email')
   for row in rows:
    row_num += 1
    for col_num in range(len(row)):
        ws.write(row_num, col_num, row[col_num], font_style)

   wb.save(response)
   return response

All line indentation are correct My goal is to create a file in excel format from the above code it's fine but the problem is rows and columns are not inter changing

If you people suggest me any other library to do excel export file that can able to transpose the data


Solution

  • def export_users_xls(request):
       response = HttpResponse(content_type='application/ms-excel')
       response['Content-Disposition'] = 'attachment; 
     filename="users.xls"'
    
      wb = xlwt.Workbook(encoding='utf-8')
      ws = wb.add_sheet('Users')
    
       # Sheet header, first row
       row_num = 0
    
      font_style = xlwt.XFStyle()
      font_style.font.bold = True
    
      columns = ['Username', 'First name', 'Last name', 'Email address', ]
    
      for col_num in range(len(columns)):
        ws.write(col_num, row_num, columns[col_num], font_style)
    
      # Sheet body, remaining rows
     font_style = xlwt.XFStyle()
    
       rows = User.objects.all().values_list('username', 'first_name', 'last_name', 'email')
     for row in rows:
      row_num += 1
      for col_num in range(len(row)):
          ws.write(col_num+1, row_num, row[col_num], font_style)
    
     wb.save(response)
     return response
    

    All lineindentation are correct