JAVA指定模板下载
后端代码:
/** * 模板下载 * * @param request * @param response * @throws IOException */ @ResponseBody @RequestMapping("/download") public void download(HttpServletRequest request, HttpServletResponse response) throws IOException { OutputStream out = null; FileInputStream in = null; try { String fileName = "人员信息模板"; // 读取模板 String excelPath = request.getSession().getServletContext() .getRealPath("/Excel/人员信息表.xlsx"); fileName = URLEncoder.encode(fileName, "UTF-8"); response.reset(); // 追加时间 response.addHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx"); response.setContentType("application/octet-stream;charset=UTF-8"); out = response.getOutputStream(); in = new FileInputStream(excelPath); byte[] b = new byte[1024]; int len; while ((len = in.read(b)) > 0) { response.getOutputStream().write(b, 0, len); } out.flush(); } catch (Exception e) { e.printStackTrace(); } finally { if (null != in) { in.close(); in = null; } if (null != out) { out.close(); out = null; } } }
前端代码:
a class="btn btn-info" href="${basePath}/electricMerchant/download" id="download">模板下载</a>
模版文件放置位置如图所示: