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>
相关推荐
降临-max5 分钟前
JavaWeb企业级开发---Mybatis
java·开发语言·笔记·学习·mybatis
小妖66616 分钟前
excel 本地sheet往服务器上粘贴时,表格宽度没有粘过来
excel
好好研究30 分钟前
SpringBoot注解的作用
java·spring boot·spring
Libby博仙1 小时前
Spring Boot 条件化注解深度解析
java·spring boot·后端
我是小疯子661 小时前
深入解析C++右值引用与移动语义
java·开发语言·算法
better_liang1 小时前
每日Java面试场景题知识点之-JUC锁的底层原理
java·并发编程·juc·锁机制·reentrantlock·readwritelock·底层原理
悟能不能悟1 小时前
Elastic Stack 中两种主要查询语言 KQL (Kibana Query Language) 和 Lucene 的详细对比和解释。
java·开发语言
我是一只小青蛙8881 小时前
Java连接MySQL数据库实战指南
java
夏末4721 小时前
Java异常处理终极指南:从入门到企业级实战,让程序稳如老狗!
java·java ee
子非鱼9211 小时前
SpringBoot快速上手
java·spring boot·后端