2017-12-20 9 views
1

iは 私の目標は、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 

すべての行のインデントを転置するために苦労していたサンプルコードでDjangoのExcelエクスポート・ファイル内の行と列を転置します上記のコードからフォーマットは、それは大丈夫ですが、問題は、行であり、あなたの人々はあなただけのWAを想定すると、データ

答えて

1
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は、上記のコードの実行後

1

を移調することができエクスポートファイルをエクセル行うために私に他のライブラリを示唆している場合、列は

を変更する間はありませんシート内のデータを転置(そしてdjango-excelがこの同じ機能を持っていると仮定した場合)にするのnt:

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

正しい私は、このエラー例外値を得た:「シート」オブジェクトが持っています属性 'get'がありません –

+0

@Access_Doomer、入力データに問題があり、辞書が必要です。 – chfw

+0

rows = User.objects.all()。values_list( 'username'、 'first_name'、 'last_name ....... –

関連する問題