1、任务需求
2、代码实现
<button οnclick="download();" style="color:red;">进线和踩线导入模板下载</button>
function download(){
var url = "../conf/excelOut";
url = encodeURI(url);
location.href = url;
}
@RequestMapping( value = "/excelOut")
public void excelStandardTemplateOut(HttpServletRequest request,
HttpServletResponse response) throws IOException{
URL save = Thread.currentThread().getContextClassLoader().getResource("");
String str = "";
str = request.getRealPath("/") +"demo/template.xls";//获取文件相对路径
File f = new File(str);
// 设置response参数,可以打开下载页面
response.reset();
response.setContentType("application/vnd.ms-excel;charset=utf-8");
try {
response.setHeader("Content-Disposition", "attachment;filename="+ new String(("进线和踩线导入模板" + ".xls").getBytes(), "iso-8859-1"));//下载文件的名称
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
ServletOutputStream out = response.getOutputStream();
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(f));
bos = new BufferedOutputStream(out);
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} catch (final IOException e) {
throw e;
} finally {
if (bis != null)
bis.close();
if (bos != null)
bos.close();
}
}