前端代码:
<a :href="'/api/campaign-api/coupon/down'" download="down.xlsx">下载</a>
后端代码:
1.接口
@ApiOperation(value = "下载") @GetMapping("/down") public void downTemplate(HttpServletResponse response) { String fileName = "down.xlsx"; couponService.down(response, fileName); }
2.实现类
public void down(HttpServletResponse response ,String filename) { // 读取要下载的文件,保存到文件输入流 FileInputStream in = null; OutputStream out = null; try { // 要下载的目标文件 File file = new File("src\\main\\resources\\static" + "\\" + filename); // 如果文件不存在 if (!file.exists()) { throw new BusinessException("Could not read file"); } // 设置响应头,控制浏览器下载该文件 response.setHeader("Content-Disposition", "attachment;filename="+filename); response.setHeader("Content-Type", "application/octet-stream;charset=UTF-8"); response.setContentType("application/octet-stream"); in = new FileInputStream(file); // 创建输出流 out = response.getOutputStream(); // 创建缓冲区 byte buffer[] = new byte[1024]; int len = 0; // 循环将输入流中的内容读取到缓冲区当中 while ((len = in.read(buffer)) > 0) { // 输出缓冲区的内容到浏览器,实现文件下载 out.write(buffer, 0, len); } // 关闭文件输入流 in.close(); // 关闭输出流 out.close(); } catch (Exception e) { e.printStackTrace(); } }
正确流程:1.获取到数据 2.解析到excle中 3.将解析的excel转换成输出流到前端,仅表示个人看法?
没看到对excel文件的操作,感觉你流程就不对?