模板文件放在resources目录下
public void downloadTemplate(HttpServletResponse response) {
String path = "/excel/模板.xlsx";
InputStream inputStream = null;
OutputStream outputStream = null;
try {
ClassPathResource classPathResource = new ClassPathResource(path);
if (!classPathResource.exists()) {
throw new Exception("模板不存在");
}
//读取要下载的文件,保存到文件输入流
inputStream = classPathResource.getInputStream();
outputStream = response.getOutputStream();
response.reset();
response.setContentType("application/octet-stream");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("模板.xlsx", "utf-8"));
byte[] buff = new byte[1024];
int i = 0;
while ((i = inputStream.read(buff)) != -1) {
outputStream.write(buff, 0, i);
outputStream.flush();
}
} catch (Exception e) {
throw new Exception("模板下载失败");
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
throw new Exception("模板下载失败");
}
}
}