springBoot + vue3 + element plus + ts + vite 实现 文件导出
后台第三方jar使用easyexcel 3.0.5
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>${easyexcel.version}</version>
</dependency>
后端代码实现:
@GetMapping("export")
public void exportDailyWeekly(HttpServletResponse response,WrDailyReportQuery query) {
String fileName = "周报数据.xlsx";
response.setContentType("application/x-www-form-urlencoded");
try {
response.setHeader("Access-Control-Expose-Headers", "content-disposition");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
List<WrDailyReportVO> exportDailyWeeklyList = dailyReportService.getDailyWeekly(query);
try {
EasyExcel.write(response.getOutputStream(), WrDailyReportVO.class).sheet("周报").doWrite(exportDailyWeeklyList);
} catch (IOException e) {
e.printStackTrace();
}
}
前端vue 封装的request.ts 加上 二进制的文件处理即可
else {
// 响应数据为二进制流处理(Excel导出) 进行二进制文件处理
if (response.data instanceof ArrayBuffer) {
return response;
}
}
封装的单独的xxx.ts中
export const exportWeekly = (queryForm: any) => {
return service({
url: 'xxxx/xxx/xxx',
method: 'get',
params: queryForm,
responseType: 'arraybuffer',
});
}
最后:
const exportDailyWeekly = () => {
return exportWeekly(state.queryForm).then(res => {
const blob = new Blob([res.data], {
type: 'application/x-www-form-urlencoded;charset=utf-8',
});
const a = document.createElement('a');
const href = window.URL.createObjectURL(blob);//下载的链接
console.log("下载的链接是多少" + href);
a.href = href;
a.download = decodeURI(
res.headers['content-disposition'].split(";")[1].split('=')[1]
);//获取的后台设置
console.log(res.headers['content-disposition'])
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
window.URL.revokeObjectURL(href);
})
}
按照以上方式 即可完成excel文件下载