zoukankan      html  css  js  c++  java
  • django 生成csv文件重要代码

    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') #告诉浏览器,返回的文档是CSV文件 response['Content-Disposition'] = 'attachment; filename=unruly.csv' #响应会有一个附加的 Content-Disposition 头部,它包含有CSV文件的文件名 # Create the CSV writer using the HttpResponse as the "file." writer = csv.writer(response) writer.writerow(['Year', 'Unruly Airline Passengers']) #调用 writer.writerow ,并且传递给它一个类似 list 或者 tuple 的可迭代对象,就可以在 CSV 文件中写入一行 for (year, num) in zip(range(1995, 2006), UNRULY_PASSENGERS): writer.writerow([year, num]) return response

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

  • 相关阅读:
    Java 8的新并行API
    java lambda表达式
    用Java反射输出对象的所有属性的值
    整数划分问题
    比较常用的几个正则表达式
    bilibili的下载文件可以有多深
    vim中的宏和normal命令
    vim与正则表达式
    Manjaro软件推荐
    解决无法更新
  • 原文地址:https://www.cnblogs.com/dengyg200891/p/5401385.html
Copyright © 2011-2022 走看看