本文實(shí)例講述了python django下載大的csv文件實(shí)現(xiàn)方法。分享給大家供大家參考,具體如下:
接手他人項(xiàng)目,第一個(gè)要優(yōu)化的點(diǎn)是導(dǎo)出csv的功能,而且要支持比較多的數(shù)據(jù)導(dǎo)出,以前用php實(shí)現(xiàn)過(guò),直接寫入 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): # 準(zhǔn)備輸出 output = cStringIO.StringIO() # 寫B(tài)OM 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) #因?yàn)镾treamingHttpResponse需要一個(gè)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
假設(shè)遍歷結(jié)果集的代碼如下:
headers = ["col1", "col2", ..., "coln"] def genRows(): for obj in objList: yield [obj.col1, obj.col2, ...obj.coln] #這樣調(diào)用,返回response return outputCSV(genRows(), "file.csv", headers)
有人可能會(huì)問(wèn),為什么不用python自帶的csv.writer?因?yàn)樯傻腸sv兼容不太好啊,關(guān)于csv的兼容性,可以看前面這篇避免UTF-8的csv文件打開中文出現(xiàn)亂碼的方法。
參考:http://stackoverflow.com/questions/5146539/streaming-a-csv-file-in-django
希望本文所述對(duì)大家基于Django框架的Python程序設(shè)計(jì)有所幫助。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
