在Python的Django框架中生成CSV文件的方法

961次阅读  |  发布于5年以前

CSV 是一种简单的数据格式,通常为电子表格软件所使用。 它主要是由一系列的表格行组成,每行中单元格之间使用逗号(CSV 是 逗号分隔数值(comma-separated values) 的缩写)隔开。例如,下面是CSV格式的"不守规矩"的飞机乘客表。


    Year,Unruly Airline Passengers
    1995,146
    1996,184
    1997,235
    1998,200
    1999,226
    2000,251
    2001,299
    2002,273
    2003,281
    2004,304
    2005,203
    2006,134
    2007,147

备注

前面的列表包含真实数据。 这些数据来自美国 联邦航空管理局。

CSV格式尽管看起来简单,却是全球通用的。 但是不同的软件会生成和使用不同的 CSV 的变种,在使用上会有一些不便。 幸运的是, Python 使用的是标准 CSV 库, csv ,所以它更通用。

因为 csv 模块操作的是类似文件的对象,所以可以使用 HttpResponse 替换:


    import csv
    from django.http import HttpResponse

    # Number of unruly passengers each year 1995 - 2005. In a real application
    # this would likely come from a database or some other back-end data store.
    UNRULY_PASSENGERS = [146,184,235,200,226,251,299,273,281,304,203]

    def unruly_passengers_csv(request):
      # Create the HttpResponse object with the appropriate CSV header.
      response = HttpResponse(mimetype='text/csv')
      response['Content-Disposition'] = 'attachment; filename=unruly.csv'

      # Create the CSV writer using the HttpResponse as the "file."
      writer = csv.writer(response)
      writer.writerow(['Year', 'Unruly Airline Passengers'])
      for (year, num) in zip(range(1995, 2006), UNRULY_PASSENGERS):
        writer.writerow([year, num])

      return response

代码和注释可以说是很清楚,但还有一些事情需要特别注意:

在任何需要返回非 HTML 内容的时候,都需要经过以下几步: 创建一个 HttpResponse 响应对象(需要指定特殊的 MIME 类型),它它传给需要处理文件的函数,然后返回这个响应对象。

Copyright© 2013-2020

All Rights Reserved 京ICP备2023019179号-8