1. Project structure (Excel template address)
2. Backend code
Where ClassPathResource is org.springframework.core.io.ClassPathResource;
-
/**
-
* Work hours Excel template download
-
* @param response
-
*/
-
@RequestMapping("/workHoursExcel")
-
public void downloadWorkHourRecordTemplate(HttpServletResponse response) {
-
try {
-
Resource resource = new ClassPathResource( "WorkHoursRecordTemplate/Excel batch import work hour template.xlsx" );
-
File file = resource.getFile();
-
String filename = resource.getFilename();
-
InputStream inputStream =
new FileInputStream(file);
-
//Force download does not open
-
response.setContentType(
"application/force-download");
-
OutputStream out = response.getOutputStream();
-
//Use URLEncoder to prevent garbled file names or read errors
-
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. Front end
<a href='/easypoi/workHoursExcel'></a>