如何在 Django excel 导出文件中转置行和列

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

这是我正在努力转置数据的示例代码

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

所有行缩进都是正确的 我的目标是根据上面的代码创建一个 excel 格式的文件,这很好,但问题是行和列没有相互改变

如果你们建议我使用任何其他库来做excel 可以转置数据的导出文件

假设您只想转置 sheet 中的数据(并假设 django-excel 具有相同的功能):

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 |
# +------+---+---+---+
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

所有行缩进都是正确的