java 从resource下载excel打不开

java 复制代码
    @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添加插件

XML 复制代码
<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>
相关推荐
程序员小杰@17 分钟前
Java 统一报文转换 + 签名验签完整介绍
java·开发语言
小张成长计划..36 分钟前
【Linux】44:五种IO模型与非阻塞IO
java·服务器·数据库
不甘平凡的小鸟44 分钟前
vs code 打开spring boot项目
java·spring boot·后端
ZhengEnCi1 小时前
Java 内存泄漏怎么排查:jstat、heap dump 与 MAT 线上定位流程
java·jvm·性能优化
Shaoshing2 小时前
LeetCode 921.使括号括号有效的最少添加
java·算法·leetcode·职场和发展
我命由我123452 小时前
Excel - Excel 固定列,滚动时该列始终可见
运维·学习·职场和发展·excel·职场发展·运维开发·学习方法
赤生云电竞2 小时前
云电竞GPU虚拟化选型:vGPU与直通架构实践对比
java·开发语言·架构
灵析表格3 小时前
灵析表格函数精讲|xml转json:供应商配置转换
xml·json·excel·办公自动化·wps·效率工具·ai办公
Ryan-Zhong3 小时前
视频解析 API 拒绝解析怎么判定:reason 分流与门禁
java·数据库·音视频
吹什么轩3 小时前
c++高并发内存池(一):从objectpool到central cache
java·开发语言