測試管理平台需要增加導出用例成Excel的功能,有兩種方式
一種是:Django獲取數據先生成本地文件,讀取本地文件后再傳遞給前端
還一種是:Django獲取數據,生成文件流,文件流傳給前端
第一種資料比較多,但是要每次下載都要在本地生成文件,太過繁瑣,這邊選擇第二種方式
步驟:
先處理Django后端
這邊使用的是openpyxl
wb = Worbook() ws = wb.active ..... /* ws是個worksheet對象,我的目的是將其變成二進制數據 通過BytesIO()來處理 from io import BytesIO */ output = BytesIO() wb.save(output) #這句是將worksheet保存到二進制字節中去 output.seek(0) #output讀取所以數據 response = FileResponse(output) #定義FileResponse,里面傳字節流進去 /* 最后返回的是response文件流,我的文件名想單獨字段傳遞給前端,咋辦 通過加response的headers來處理 還有文件名中文亂碼咋搞,通過escape_uri_path來處理 */ tname = "你好喲" tname = escape_uri_path(tname) fileName = tname + time.strftime("%y%m%d%H%M%S") + '.xlsx' response['name'] = fileName response['Access-Control-Expose-Headers'] = 'name' #這個name是上一句的key response['Content-Type'] = 'applecation/octet-stream' #這邊不加Content-Disposition也可以 return response
明天更新前端的處理
-------------------------------------------
前端需要處理兩個,一個是請求參數這么設置,還一個是相應和文件名咋處理
請求參數ajax需要設置responseType: 'blob'
this.$axios({
method: "post",
url: "/test/export/",
data: this.exportData,
responseType: 'blob'
}).then(function(res){
/*
其實就是通過創建a標簽來處理打開href鏈接來下載,最后在移除a標簽就行
*/
let url = window.URL.createObjectURL(res.data)//res.data就是接口返回的文件對象
let a = document.createElement('a')
a.href = url
a.download = decodeURI(res.headers.name)//res.headers.nam就可以獲取自定義的名稱,再解碼
document.body.appendChild(a)
a.click()
window.URL.revokeObjectURL(url)
document.body.removeChild(a)
})