SpringBoot下载resource下的文件(POI)
1、导入依赖
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-poi</artifactId>
<version>${hutool.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>${poi.version}</version>
</dependency>
2、编写controller
@ApiOperation(value = "下载默认模板文件", notes = "下载默认模板文件")
@GetMapping(value = "/excel-template/{sort}")
public void downloadHeadTemplate(@PathVariable("sort") String sort) throws Exception {
HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
response.setCharacterEncoding("UTF-8");
String fileName = sort+"模板.xlsx";
String template;
template = "/excel/reset_default_setting.xlsx";
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename=" + encodeFileName(fileName));
try (InputStream inStream = MedalController.class.getResourceAsStream(template);
OutputStream outputStream = response.getOutputStream()) {
byte[] b = new byte[1000];
int len;
while ((len = inStream.read(b)) > 0) {
outputStream.write(b, 0, len);
}
} catch (IOException e) {
log.warn("MedalController getExcelTemplate put content failed,cause:{}", e);
}
}
3、校验浏览器,改变文件名
private String encodeFileName(String fileName) {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String codeFileName = null;
String agent = request.getHeader("User-Agent");
try {
if (agent.contains("MSIE") || agent.contains("Trident")) {
codeFileName = java.net.URLEncoder.encode(fileName, "UTF-8");
} else {
codeFileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
}
} catch (Exception e) {
e.printStackTrace();
}
return codeFileName;
}