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

944 Views Asked by At

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

2

There are 2 best solutions below

0
On BEST ANSWER
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

3
On

Assuming you just want to transpose data in a sheet (And assuming django-excel has this same function):

import pyexcel as p
my_dic = { "col1": [1, 2, 3], "col2": [4, 5, 6], "col3": [7, 8, 9]}
sheet = p.get_sheet(adict=my_dic)

# sheet now is this:
# pyexcel_sheet1:
# +------+------+------+
# | col1 | col2 | col3 |
# +------+------+------+
# | 1    | 4    | 7    |
# +------+------+------+
# | 2    | 5    | 8    |
# +------+------+------+
# | 3    | 6    | 9    |
# +------+------+------+

sheet.transpose()

# sheet now is this:
# pyexcel_sheet1:
# +------+---+---+---+
# | col1 | 1 | 2 | 3 |
# +------+---+---+---+
# | col2 | 4 | 5 | 6 |
# +------+---+---+---+
# | col3 | 7 | 8 | 9 |
# +------+---+---+---+