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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在Django excel导出文件中转置行和列相关的知识,希望对你有一定的参考价值。

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

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导出文件,可以转置数据

答案

假设您只想在表格中转置数据(假设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

所有lineindentation都是正确的

以上是关于如何在Django excel导出文件中转置行和列的主要内容,如果未能解决你的问题,请参考以下文章

SQL for MS ACCESS 链接表转置行和列

用awk转置行和列

当 BigQuery 中没有任何“id”类型列时转置行和列

如何在 PostgreSQL 中转置列和行(即如何切换行和列)? [复制]

报表导出excel锁定行和列

如何在 MVC 应用程序中转置 Kendo UI 网格中的行和列?