前言
简单记录一下,excel文件导出下载功能
一、后端接口返回excel文件
把自己生成的workbook 以文件流的方式,返回前台
Workbook workbook = employeeConfirmationDefectService.exportPoorPolishExcel(budatBegin, budatEnd, queryWrapper); //传输到前端下载 try { response.setHeader("content-Type", "application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("抛光不良记录.xlsx", "UTF-8")); workbook.write(response.getOutputStream()); workbook.close(); } catch (IOException e) { throw new RuntimeException(e); }
二、前端接受文件流,下载文件
发送post请求,设定responseType: ‘blob’,指定响应数据为文件对象
export function postExcelExport(url,parameter) { let sign = signMd5Utils.getSign(url, parameter); //将签名和时间戳,添加在请求接口 Header let signHeader = {"X-Sign": sign,"X-TIMESTAMP": signMd5Utils.getDateTimeToString()}; return axios({ url: url, method:'post' , params: parameter, headers: signHeader, responseType: 'blob' })}
调用导出方法,发送请求
//导出下载excel文件handleExportXls() { this.loading = true postExcelExport(this.url.export, this.queryParam) .then((data) => { console.log(data) if (!data) { this.$message.warning('文件下载失败') return } if (typeof window.navigator.msSaveBlob !== 'undefined') { window.navigator.msSaveBlob( new Blob([data], { type: 'application/vnd.ms-excel;charset=utf8' }), '文件名' + '.xls' ) } else { let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel;charset=utf8' })) let link = document.createElement('a') link.style.display = 'none' link.href = url link.setAttribute('download', '文件名' + '.xls') document.body.appendChild(link) link.click() document.body.removeChild(link) //下载完成移除元素 window.URL.revokeObjectURL(url) //释放掉blob对象 } }) .finally(() => { this.loading = false }) },