代码之家  ›  专栏  ›  技术社区  ›  user3114168

django-将字典列表导出到csv

  •  0
  • user3114168  · 技术社区  · 6 年前

    我在views.py中创建了一个字典列表,

    my_list= [
    {'user': 1000, 'account1': 100, 'account2': 200, 'account3': 100},
    {'user': 1001, 'account1': 110, 'account2': 100, 'account3': 250},
    {'user': 1002, 'account1': 220, 'account2': 200, 'account3': 100},
    ]
    

    我想把它导出到csv文件。

        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = 'attachment; filename="mylist.csv"'
    
        writer = csv.writer(response)
        for data in my_list:
            writer.writerow(data)
    
        return response
    

    我知道“我的清单中的数据”有错误。 我的\列表包含所有键和值。

    如何只获取我的\列表的密钥?或者有其他方法可以将列表导出到csv?

    (我用的是Django2和python3.4)

    1 回复  |  直到 6 年前
        1
  •  1
  •   Rakesh    6 年前

    你需要 DictWriter

    演示:

    import csv
    my_list= [
    {'user': 1000, 'account1': 100, 'account2': 200, 'account3': 100},
    {'user': 1001, 'account1': 110, 'account2': 100, 'account3': 250},
    {'user': 1002, 'account1': 220, 'account2': 200, 'account3': 100},
    ]
    
    with open(filename, "w") as infile:
        writer = csv.DictWriter(infile, fieldnames=my_list[0].keys())
        writer.writeheader()
        for data in my_list:
            writer.writerow(data)
    
    with open(filename, 'rb') as infile:
        response = HttpResponse(infile, content_type='text/csv')
        response['Content-Disposition'] = 'attachment; filename=mylist.csv'
        return response