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>
相关推荐
木井巳4 分钟前
【动态规划: 子序列问题】最长递增子序列的个数
java·算法·leetcode·动态规划·推荐算法
nice_lcj52042 分钟前
Spring 核心串讲:把 IoC、AOP、Boot、事务连成体系
java·spring boot·spring·面试·ioc·aop·体系串讲
nice_lcj5201 小时前
Spring Boot 入门:几行配置怎么跑起来
java·spring boot·spring·面试·自动配置·起步依赖
艾莉丝努力练剑2 小时前
【AI大模型接入SDK】项目总结
java·开发语言·前端·c++·人工智能·学习·架构
Resean02232 小时前
SpringCloud 源码分析(二)Nacos 注册中心(上):服务注册流程与注册表模型
java·后端·spring·spring cloud
TDengine (老段)2 小时前
TDengine IDMP ---- Excel 插件
大数据·数据库·excel·时序数据库·tdengine·涛思数据
SimonKing3 小时前
别OCR了,都在用了OXR了,看那看那这款开源的OXR产品
java·后端·程序员
lusklusklusk3 小时前
图文详解:使用 Power BI Desktop 一步步创建并部署跨 Excel 与 SQL 数据的 PBIRS 报表
数据库·sql·excel
Rain的Java大神之路3 小时前
DTO、VO、PO 到底要不要拆?这场 Java 分层之争,今天一次讲透
java·后端·面试
CoderYanger3 小时前
Java EE 进阶:14.案例综合练习-博客系统(第三弹) :用户登录+强制登录
java·服务器·开发语言·数据库·spring boot·java-ee·mybatis