前言
在工作中,我們經常需要導出數據庫中或固定格式的數據。這個時候我們就要用到pandas來進行數據的處理了。pandas是一個非常優秀的python數據處理工具。
獲取數據
# 從前端獲取到的參數
starttime = request.data.get('starttime') # 開始時間
endtime = request.data.get('endtime') # 結束時間
# 獲取評論模型中對應的數據 (判斷就我就不寫了,正式環境下盡量去寫)
com = Comment.objects.filter(timestamp__gte=strattime,timestamp__let=endtime)
comment_list = com.values_list() # 獲取序列化后的評論數據
使用pandas進行數據的處理
這里使用了pandas庫的一個
DataFrame
數據集,里面的參數主要有 data, index, columns, dtype, copy
經常使用的都有 data 和 columns 一個是數據源,一個是表頭
to_excel
就是寫入到哪個文件,他的參數是文件
io.BytesIO 這里使用這個主要是為了吧數據轉為二進制文件流返回給前端進行下載
import pandas as pd # 導入pandas 並重命名 pd
import io
data = pd.DataFrame(comment_list)
data.columns(['時間','點贊數','標題','評論']) # 設置excel表頭
output = io.BytesIO() # 配置一個BytesIO 這個是為了轉二進制流
data.to_excel(output, index=False) # index=False 是為了不建立索引
output.seek(0) # 把游標歸0
返回二進制流
response = HttpResponse() # 創建一個HttpResponse
response["Content-Type"] = "application/vnd.ms-excel" # 類型
file_name = 'comment.xlsx' # 文件名稱 自定義
response['Content-Disposition'] = 'attachment;filename=%s' % file_name
response.write(output.getvalue()) # 寫入數據
output.close() # 關閉
return response # 返回
總結
使用pandas最主要的是處理數據的結構。導出的話還是配合二進制流進行返回
若是數據量比較大的時候,盡量不要使用io.BytesIO() 去轉二進制了,這樣會浪費太多的時間,我們可以先這樣后那樣的去節省時間,未完待續。