场景:由于需要使用poi进行数据的导入和导出,在导入的时候excel的格式是很严格的,所以我们需要提供一个excel模板让运维人员添加数据然后再上传,这样格式就不会有问题了,虽然功能简单,但是copy了很多代码都是有问题的,最后好不容易找到个可以用的,分享一下
实现方法:
1.文件位置位于resoures文件夹下
2.源码
@RequestMapping("/download")
public void downloadFile(HttpServletResponse response) throws IOException {
try {
Resource resource = new ClassPathResource("poi/运费模板.xlsx");
File file = resource.getFile();
String filename = resource.getFilename();
InputStream inputStream = new FileInputStream(file);
//强制下载不打开
response.setContentType("application/force-download");
OutputStream out = response.getOutputStream();
//使用URLEncoder来防止文件名乱码或者读取错误
response.setHeader("Content-Disposition", "attachment; filename="+URLEncoder.encode(filename, "UTF-8"));
int b = 0;
byte[] buffer = new byte[1000000];
while (b != -1) {
b = inputStream.read(buffer);
if(b!=-1) out.write(buffer, 0, b);
}
inputStream.close();
out.close();
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
说明:springboot中可以使用ClassPathResource类来直接获取resources中的文件