首页 > 编程 > Python > 正文

python django下载大的csv文件实现方法分析

2019-11-25 12:18:17
字体:
来源:转载
供稿:网友

本文实例讲述了python django下载大的csv文件实现方法。分享给大家供大家参考,具体如下:

接手他人项目,第一个要优化的点是导出csv的功能,而且要支持比较多的数据导出,以前用php实现过,直接写入php://output就行了,django怎么做呢?如下:

借助django的StreamingHttpResponse和python的generator

def outputCSV(rows, fname="output.csv", headers=None):  def getContent(fileObj):    fileObj.seek(0)    data = fileObj.read()    fileObj.seek(0)    fileObj.truncate()    return data  def genCSV(rows, headers):    # 准备输出    output = cStringIO.StringIO()    # 写BOM    output.write(bytearray([0xFF, 0xFE]))    if headers != None and isinstance(headers, list):      headers = codecs.encode("/t".join(headers) + "/n", "utf-16le")      output.write(headers)      yield getContent(output)    for row in rows:      rowData = codecs.encode("/t".join(row) + "/n", "utf-16le")      output.write(rowData)      yield getContent(output) #因为StreamingHttpResponse需要一个Iterator    output.close()  resp = StreamingHttpResponse(genCSV(rows, headers))  resp["Content-Type"] = "application/vnd.ms-excel; charset=utf-16le"  resp["Content-Type"] = "application/octet-stream"  resp["Content-Disposition"] = "attachment;filename=" + fname  resp["Content-Transfer-Encoding"] = "binary"  return resp

假设遍历结果集的代码如下:

headers = ["col1", "col2", ..., "coln"]def genRows():      for obj in objList:        yield [obj.col1, obj.col2, ...obj.coln]   #这样调用,返回responsereturn outputCSV(genRows(), "file.csv", headers)

有人可能会问,为什么不用python自带的csv.writer?因为生成的csv兼容不太好啊,关于csv的兼容性,可以看前面这篇避免UTF-8的csv文件打开中文出现乱码的方法

参考:http://stackoverflow.com/questions/5146539/streaming-a-csv-file-in-django

希望本文所述对大家基于Django框架的Python程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表