下载excel模板

时间:2024-04-15 19:46:46
/** * 下载模板 * @param response * @return */ @SneakyThrows @GetMapping("/downloadTemplate") public void downloadTemplate(HttpServletResponse response){ String fileName = "指标体系导入模板.xlsx"; ServletOutputStream out = response.getOutputStream(); try{ //文件在项目中的存放路径 String filePath = getClass().getResource("/static/" + fileName).getPath(); // 文件路径就是上图添的位置 filePath = URLDecoder.decode(filePath, "UTF-8"); //设置响应 response.setHeader("content-Type", "application/vnd.ms-excel"); response.setHeader("Accept-Ranges", "bytes"); response.setHeader("Content-Disposition", "attachment;fileName=" + fileName); FileInputStream inputStream = new FileInputStream(filePath); int b = 0; byte[] buffer = new byte[1024]; while ((b = inputStream.read(buffer)) != -1) { // 写到输出流(out)中 out.write(buffer, 0, b); } inputStream.close(); }catch (Throwable e){ e.printStackTrace(); }finally{ try { if (out != null) { out.flush(); out.close(); } } catch (IOException e) { e.printStackTrace(); } } }