1.项目结构(Excel模板地址)
2.后端代码
其中ClassPathResource为org.springframework.core.io.ClassPathResource;
/**
* 工时Excel模板下载
* @param response
*/
@RequestMapping("/workHoursExcel")
public void downloadWorkHourRecordTemplate(HttpServletResponse response) {
try {
Resource resource = new ClassPathResource("WorkHoursRecordTemplate/Excel批量导入工时模板.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();
}
}
3.前端
<a href='/easypoi/workHoursExcel'></a>