本文實例講述了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]
#這樣調用,返回response
return 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程序設計有所幫助。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

