后端代码
@GetMapping(value = "/excelList",produces = "application/vnd.ms-excel;charset=utf-8")
public void excelList(HttpServletResponse response) throws IOException {
List<TUsers2> list = tUsersService.getLists();
ExcelWriter writer = ExcelUtil.getWriter();
writer.addHeaderAlias("name", "姓名");
writer.addHeaderAlias("age", "年龄");
writer.addHeaderAlias("money", "账户余额");
writer.addHeaderAlias("id", "id");
writer.setOnlyAlias(true);//导出指定别名的列
writer.merge(3, "hutool报表");
writer.write(list, true);
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename=" + System.currentTimeMillis() + ".xls");
ServletOutputStream out = response.getOutputStream();
writer.flush(out, true);
out.close();
}
前端代码
axios.get(`http://localhost:8080/v1/excelList`, { //url: 接口地址
params: this.queryParam,
responseType: `arraybuffer` //一定要写
}).then(res => {
if (res.status == 200) {
let blob = new Blob([res.data], {
type: 'application/vnd.ms-excel;charset=utf-8'
});
let objectUrl = URL.createObjectURL(blob)
window.location.href = objectUrl
}
})