1.配置文件: pom.xml中添加依賴: <!-- thymeleaf模版 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> application.yml文件中添加要下載的模板文件存放地址添加讀取配置的模板存放地址
2.前台代碼 <a href="javascript:downTemple()" style="color:#1c99ef;text-decoration:underline;">下載模板</a> function downTemple(){ window.location.href="/UserController/downTemple"; }
3.后台代碼 @RequestMapping(value = "/downTemple") public String downTemple(HttpServletResponse response, RedirectAttributes redirectAttributes) { String fileName = "用戶信息模板.xlsx";// 設置文件名,根據業務需要替換成要下載的文件名 if (fileName != null) { //設置文件路徑 String realPath = configProperties.getExcelTemplateDpwloadPath();//這里使用配置類配置文件路徑 File file = new File(realPath , fileName); if (file.exists()) { try { response.setContentType("application/force-download");// 設置強制下載不打開 fileName =java.net.URLDecoder.decode(fileName,"UTF-8"); response.addHeader("Content-Disposition", "attachment;fileName=" + new String(fileName.getBytes("GB2312"),"iso8859-1"));// 設置文件名 中文要編碼后才可以 } catch (UnsupportedEncodingException e1) { // TODO 自動生成的 catch 塊 e1.printStackTrace(); } byte[] buffer = new byte[1024]; FileInputStream fis = null; BufferedInputStream bis = null; try { fis = new FileInputStream(file); bis = new BufferedInputStream(fis); OutputStream os = response.getOutputStream(); int i = bis.read(buffer); while (i != -1) { os.write(buffer, 0, i); i = bis.read(buffer); } } catch (Exception e) { e.printStackTrace(); } finally { if (bis != null) { try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } } } return null; }

添加讀取配置的模板存放地址