一、添加依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.1.0</version>
</dependency>
二、编写接口
@GetMapping("/downloadTemplate")
public void downloadTemplate(HttpServletRequest request,
HttpServletResponse response){
String fileName = "template"+File.separator+"字段标准导入模板.xlsx";
InputStream is = ClassLoader.getSystemResourceAsStream(fileName);
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("utf-8");
Workbook wb = null;
try {
wb = new XSSFWorkbook(is);
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
wb.write(response.getOutputStream());
} catch (Exception e) {
log.error("下载导入模板异常{}", e.getMessage());
} finally {
IOUtils.closeQuietly(wb);
if(is!=null){
try {
is.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
三、这种代码,在windows上调试没问题,打成jar包发到linux环境上会有问题,改成如下代码就行:
@GetMapping("/downloadTemplate")
public void downloadTemplate(HttpServletRequest request,
HttpServletResponse response){
String fileName = "template"+File.separator+"ColumnStandardImportTemplate.xlsx";
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("utf-8");
try (InputStream is = new ClassPathResource(fileName).getInputStream();
Workbook wb = new XSSFWorkbook(is);
ServletOutputStream os = response.getOutputStream()) {
wb.write(os);
os.flush();
} catch (Exception e) {
log.error("下载导入模板异常", e);
}
}