国产成人精品久久免费动漫-国产成人精品天堂-国产成人精品区在线观看-国产成人精品日本-a级毛片无码免费真人-a级毛片毛片免费观看久潮喷

您的位置:首頁技術文章
文章詳情頁

在django項目中導出數據到excel文件并實現下載的功能

瀏覽:73日期:2022-07-06 16:05:46

依賴模塊

xlwt下載:pip install xlwt

后臺模塊

view.py

# 導出Excel文件def export_excel(request): city = request.POST.get(’city’) print(city) list_obj=place.objects.filter(city=city) # 設置HTTPResponse的類型 response = HttpResponse(content_type=’application/vnd.ms-excel’) response[’Content-Disposition’] = ’attachment;filename=’+city+’.xls’ '''導出excel表''' if list_obj: # 創建工作簿 ws = xlwt.Workbook(encoding=’utf-8’) # 添加第一頁數據表 w = ws.add_sheet(’sheet1’) # 新建sheet(sheet的名稱為'sheet1') # 寫入表頭 w.write(0, 0, u’地名’) w.write(0, 1, u’次數’) w.write(0, 2, u’經度’) w.write(0, 3, u’緯度’) # 寫入數據 excel_row = 1 for obj in list_obj: name = obj.place sum = obj.sum lng = obj.lng lat = obj.lat # 寫入每一行對應的數據 w.write(excel_row, 0, name) w.write(excel_row, 1, sum) w.write(excel_row, 2, lng) w.write(excel_row, 3, lat) excel_row += 1 # 寫出到IO output = BytesIO() ws.save(output) # 重新定位到開始 output.seek(0) response.write(output.getvalue()) return response

前端模塊

<button type='button' >導出excel</button>

$('#export_excel').click(function () { var csrf=$(’input[name='csrfmiddlewaretoken']’).val(); const req = new XMLHttpRequest(); req.open(’POST’, ’/export_excel/’, true); req.responseType = ’blob’; req.setRequestHeader(’Content-Type’, ’application/x-www-form-urlencoded’); //設置請求頭 req.send(’city=’+$(’#city’).val()+'&&csrfmiddlewaretoken='+csrf); //輸入參數 req.onload = function() { const data = req.response; const a = document.createElement(’a’); const blob = new Blob([data]); const blobUrl = window.URL.createObjectURL(blob); download(blobUrl) ; }; });

function download(blobUrl) { var city = $('input[name=’city’]').val(); const a = document.createElement(’a’); a.style.display = ’none’; a.download = ’<文件命名>’; a.href = blobUrl; a.click(); document.body.removeChild(a);}

補充知識:Python Django實現MySQL百萬、千萬級的數據量下載:解決memoryerror、nginx time out

前文

在用Django寫項目的時候時常需要提供文件下載的功能,而Django也是貼心提供了幾種方法:FileResponse、StreamingHttpResponse、HttpResponse,其中FileResponse和StreamingHttpResponse都是使用迭代器迭代生成數據的方法,所以適合傳輸文件比較大的情況;而HttpResponse則是直接取得數據返回給用戶,所以容易造成memoryerror和nginx time out(一次性取得數據和返回的數據過多,導致nginx超時或者內存不足),關于這三者,DJango的官網也是寫的非常清楚,連接如下:https://docs.djangoproject.com/en/1.11/ref/request-response/

那正常我們使用的是FileResponse和StreamingHttpResponse,因為它們流式傳輸(迭代器)的特點,可以使得數據一條條的返回給客戶端,文件隨時中斷和復傳,并且保持文件的一致性。

FileResponse和StreamingHttpResponse

FileResponse顧名思義,就是打開文件然后進行傳輸,并且可以指定一次能夠傳輸的數據chunk。所以適用場景:從服務端返回大文件。缺點是無法實時獲取數據庫的內容并傳輸給客戶端。舉例如下:

def download(request): file=open(’path/demo.py’,’rb’) response =FileResponse(file) response[’Content-Type’]=’application/octet-stream’ response[’Content-Disposition’]=’attachment;filename='demo.py'’ return response

從上可以發現,文件打開后作為參數傳入FileResponse,隨后指定傳輸頭即可,但是很明顯用這個來傳輸數據庫就不太方便了,所以這邊推介用StreamingHttpResponse的方式來傳輸。

這里就用PyMysql來取得數據,然后指定為csv的格式返回,具體代碼如下:

# 通過pymysql取得數據import pymysqlfield_types = { 1: ’tinyint’, 2: ’smallint’, 3: ’int’} #用于后面的字段名匹配,這里省略了大多數conn = pymysql.connect(host=’127.0.0.1’,port=3306,database=’demo’,user=’root’,password=’root’)cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)cursor.execute(sql)#獲取所有數據data = cursor.fetchall()cols = {}#獲取所有字段for i,row in enumerate(self.cursor.description): if row[0] in cols: cols[str(i)+row[0]] = field_types.get(row[1], str(row[1])) #這里的field_type是類型和數字的匹配 cols[row[0]] = field_types.get(row[1], str(row[1]))cursor.close()conn.close()#通過StreamingHttpResponse指定返回格式為csvresponse = StreamingHttpResponse(get_result_fromat(data, cols))response[’Content-Type’] = ’application/octet-stream’response[’Content-Disposition’] = ’attachment;filename='{0}'’.format(out_file_name)return response#循環所有數據,然后加到字段上返回,注意的是要用迭代器來控制def get_result_fromat(data, cols): tmp_str = '' # 返回文件的每一列列名 for col in cols: tmp_str += ’'%s',’ % (col) yield tmp_str.strip(',') + 'n' for row in data: tmp_str = '' for col in cols: tmp_str += ’'%s',’ % (str(row[col])) yield tmp_str.strip(’,’) + 'n'

整個代碼如上,大致分為三部分:從mysql取數據,格式化成我們想要的格式:excel、csv、txt等等,這邊指定的是csv,如果對其他格式也有興趣的可以留言,最后就是用StreamingHttpResponse指定返回的格式返回。

實現百萬級數據量下載

上面的代碼下載可以支持幾萬行甚至十幾萬行的數據,但是如果超過20萬行以上的數據,那就比較困難了,我這邊的剩余內存大概是1G的樣子,當超過15萬行數據(大概)的時候,就報memoryerror了,問題就是因為fetchall,雖然我們StreamingHttpResponse是一條條的返回,但是我們的數據時一次性批量的取得!

如何解決?以下是我的解決方法和思路:

用fetchone來代替fetchall,迭代生成fetchone

發現還是memoryerror,因為execute是一次性執行,后來發現可以用流式游標來代替原來的普通游標,即SSDictCursor代替DictCursor

于是整個代碼需要修改的地方如下:

cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) ===>cursor = conn.cursor(cursor=pymysql.cursors.SSDictCursor)

data = cursor.fetchall() ===>row = cursor.fetchone()

def get_result_fromat(data, cols): tmp_str = '' # 返回文件的每一列列名 for col in cols: tmp_str += ’'%s',’ % (col) yield tmp_str.strip(',') + 'n' for row in data: tmp_str = '' for col in cols: tmp_str += ’'%s',’ % (str(row[col])) yield tmp_str.strip(’,’) + 'n' =====> def get_result_fromat(data, cols): tmp_str = '' for col in cols: tmp_str += ’'%s',’ % (col) yield tmp_str.strip(',') + 'n' while True: tmp_str = '' for col in cols: tmp_str += ’'%s',’ % (str(row[col])) yield tmp_str.strip(’,’) + 'n' row = db.cursor.fetchone() if row is None: break

可以看到就是通過while True來實現不斷地取數據下載,有效避免一次性從MySQL取出內存不足報錯,又或者取得過久導致nginx超時!

總結

關于下載就分享到這了,還是比較簡單的,謝謝觀看~希望能給大家一個參考,也希望大家多多支持好吧啦網。

標簽: excel
相關文章:
主站蜘蛛池模板: 免费一级片视频 | 欧美成人高清免费大片观看 | 性色a| 男女同床爽爽视频免费 | 国产三级精品美女三级 | 97精品国产91久久久久久久 | 免费看一级欧美毛片视频 | 国产精品成人免费观看 | 老鸭窝 国产 精品 91 | 精品91一区二区三区 | 99视频有精品视频免费观看 | 波多野结衣在线观看一区二区三区 | 精品国产自 | 国产精品不卡在线 | 亚洲成a v人片在线观看 | 国产精品一区二区在线观看 | 国产精品久久久亚洲 | 成人看片免费 | 美女的让男人桶到爽软件 | 日韩精品中文字幕视频一区 | 久久九九国产 | 中国国产一级毛片视频 | 久草精彩视频 | 亚洲国产高清人在线 | 亚洲日本综合 | 一级做a爱片久久蜜桃 | 欧美一级特黄特黄做受 | 久久爽久久爽久久免费观看 | 美女黄色在线观看 | 99久久成人国产精品免费 | 精品久久久久久综合网 | 国产日韩欧美综合一区二区三区 | 日韩黄色在线 | 免费一级视频在线播放 | 99精品欧美一区二区三区美图 | 国产高清自拍视频 | 国产精品综合一区二区 | 久久99久久精品国产只有 | 国产亚洲精品久久综合影院 | 亚洲国产日韩综合久久精品 | 一级毛片大全 |