前端React後端Django 匯出Excel
阿新 • • 發佈:2021-07-01
Dajngo查詢資料,查詢出來之後生成Excel儲存本地 class ExportExcel(APIView): def post(self, request, *args, **kwargs): export_time = request.data.get('startEndTime') user_id = request.data.get('user_id') if len(user_id) == 1 and 0 in user_id: message_content = StatisticsMessageCount.objects.filter( creat_time__range=(export_time[0] + " 00:00:00", export_time[1] + " 23:59:59")) elif len(user_id) > 1 and 0 in user_id: return JsonResponse({"code": 201, "message": "匯出失敗,請把全部選項去除!"}) else: message_content = StatisticsMessageCount.objects.filter(user_id__in=user_id, creat_time__range=(export_time[0] + " 00:00:00", export_time[1] + " 23:59:59")) wb = xlwt.Workbook(encoding='utf8') sheet = wb.add_sheet('sheet', cell_overwrite_ok=True) style_heading = xlwt.easyxf(""" font: height 220; align: vert center, horiz center; pattern: pattern solid, fore-colour 0x16; borders: left thin, right thin, top thin, bottom thin """) for i in range(0, len(message_content)): sheet.col(i).width = 256 * 30 sheet.row(i).height = 20 * 80 sheet.write(0, 0, '序號', style_heading) sheet.write(0, 1, '銷售', style_heading) sheet.write(0, 2, '地區', style_heading) sheet.write(0, 3, 'Qustions', style_heading) sheet.write(0, 4, 'Answer', style_heading) sheet.write(0, 5, '解答人', style_heading) data_row = 0 file_name = None for i in message_content: # 格式化datetime data_row += 1 if len(user_id) > 1 or len(user_id) == 1 and 0 in user_id: file_name = "KPI統計" else: file_name = i.answerer sheet.write(data_row, 0, data_row) sheet.write(data_row, 1, i.sales) sheet.write(data_row, 2, i.area, ) sheet.write(data_row, 3, i.problem) sheet.write(data_row, 4, i.answer) sheet.write(data_row, 5, i.answerer, ) try: import os test_url = "http://127.0.0.1:8081" test_path = str('/medias/weekly/{}.xlsx'.format(file_name)) ret = os.getcwd() wb.save(os.getcwd() + pord_path) return JsonResponse({"code": 200, "fileName": "{}.xlsx".format(file_name), "filePath": pord_url + pord_path }) except Exception as e: print("異常: {}".format(e)) return JsonResponse({"code": 201, "message": "匯出失敗,請關閉當前本地電腦開啟的相同Excel重新匯出!"})
前端 react exportExcel = () => { const {startEndTime, selectedItems} = this.state let currentUser = JSON.parse(localStorage.getItem('userInfo')); const {dispatch} = this.props if (startEndTime.length === 2) { dispatch({ type: 'GetStaticsCount/exportExcelData', payload: { apiPath:'/wx/kpi_export/', user_id: currentUser.weights > 0? selectedItems:[currentUser.id], startEndTime }, callback: response => { // 這塊是關鍵, 根據後臺api返回的檔案路徑,在本地可以正常a標籤下載,在伺服器上不可以,直接通過連結開啟是檔案流形式 axios.post(response.filePath, '', { headers: {'Content-Type': 'application/x-www-form-urlencoded', //請求的資料型別為form data格式 }, 'responseType': 'blob' //設定響應的資料型別為一個包含二進位制資料的 Blob 物件,必須設定!!! }).then(function (response) { console.log(`資料流: ${response.data}`) const blob = new Blob([response.data]); const fileName = 'KPI統計.xlsx'; const linkNode = document.createElement('a'); linkNode.download = fileName; //a標籤的download屬性規定下載檔案的名稱 linkNode.style.display = 'none'; linkNode.href = URL.createObjectURL(blob); //生成一個Blob URL document.body.appendChild(linkNode); linkNode.click(); //模擬在按鈕上的一次滑鼠單擊 URL.revokeObjectURL(linkNode.href); // 釋放URL 物件 document.body.removeChild(linkNode); }).catch(function (error) { console.log(error); }); } }) } else { message.error("請選擇匯出時間") } }