@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文件乱码或者损坏。文章来源:https://www.toymoban.com/news/detail-689530.html
需要再maven添加插件文章来源地址https://www.toymoban.com/news/detail-689530.html
<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>
到了这里,关于java 从resource下载excel打不开的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!