@GetMapping("/download/template")public void template(HttpServletResponse response) throws IOException {ServletOutputStream outputStream = response.getOutputStream();InputStream inputStream = null;try {//从resource获取excel文件流inputStream = getClass().getClassLoader().getResourceAsStream("批量上传产品模板.xlsx");String fileName = "批量上传产品模板.xlsx";response.reset();response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");response.setCharacterEncoding("UTF-8");response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));response.setHeader("Content-Length", String.valueOf(inputStream.available()));IoUtil.copy(inputStream, outputStream);} catch (Exception e) {e.printStackTrace();throw new ServiceException("下载失败");} finally {inputStream.close();outputStream.flush();outputStream.close();}}
由于Java项目在编译/Maven打包Excel等资源文件时,使用了Maven的filter,导致打包后的Excel文件乱码或者损坏。
需要再maven添加插件
<build><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-resources-plugin</artifactId><configuration><encoding>UTF-8</encoding><nonFilteredFileExtensions><nonFilteredFileExtension>xlsx</nonFilteredFileExtension><nonFilteredFileExtension>xls</nonFilteredFileExtension></nonFilteredFileExtensions></configuration></plugin></plugins><resources><resource><directory>src/main/resources</directory><filtering>true</filtering></resource></resources>
</build>