後端代碼:
/**
* 模板下載
*
* @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>
模版文件放置位置如圖所示: