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>
相关推荐
土司大王30 分钟前
LeetCode hto100——字母异位词分组
java·算法·leetcode
码匠许师傅41 分钟前
【C++ 面试真题】聊聊 C++ 中的 lambda 表达式
java·c++·面试
QCodingDev1 小时前
Spring AI Alibaba ReAct Agent实战:从Tool Calling到Agent,企业AI复杂业务该如何设计?
java·人工智能·agent·ai编程·spring ai
灵析表格1 小时前
灵析表格财务函数深度实用性分析与实操教程
开发语言·ai·json·excel·wps
RainCity1 小时前
Java Swing 自定义组件库分享(十六)
java·笔记·后端
赵广陆3 小时前
企业实战:Markdown图片检索
android·java·开发语言
C++、Java和Python的菜鸟3 小时前
第3章 从0开始用若依
java·开发语言
Json____3 小时前
五金制品行业-企业官网源码
java·大数据·数据库·企业站·wwwoop.com
counting money4 小时前
Spring AI Alibaba 从入门到实战:构建企业级 AI 应用
java·人工智能·spring
原野池予5 小时前
深入Java集合框架:数组与List互转底层原理剖析(JDK 8)
java·数据结构·list