提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
使用springboot实现excel下载
提示:以下是本篇文章正文内容,下面案例可供参考
一、使用步骤
1.yml
在D盘下放你要下载的excel文件
templates:
whitepath: D:\\template.xlsx
2.controller
@RequestMapping("/download")
public CommRetVo downloadWorkHourRecordTemplate(HttpServletResponse response) {
CommRetVo commRetVo = new CommRetVo();
try {
// Resource resource = new ClassPathResource("static/excelTemplate/template.xlsx");\
// Resource resource = new ClassPathResource(templateswhitepath);
File file = new File(templateswhitepath);
String filename = "template.xlsx";
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();
commRetVo.setCode("1");
commRetVo.setMsg("下载成功");
} catch (IOException e) {
e.printStackTrace();
commRetVo.setCode("0");
commRetVo.setMsg("失败");
}
return commRetVo;
}