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>
相关推荐
YC运维3 分钟前
Kubernetes资源管理全解析
java·容器·kubernetes
Sam_Deep_Thinking23 分钟前
EasyExcel 流式处理中实现末尾行过滤的技术方案
excel
rexling129 分钟前
【Spring Boot】Spring Boot解决循环依赖
java·前端·spring boot
武子康42 分钟前
Java-163 MongoDB 生产安全加固实战:10 分钟完成认证、最小权限、角色详解
java·数据库·分布式·mongodb·性能优化·系统架构·nosql
ZIM学编程1 小时前
「学长有话说」作为一个大三学长,我想对大一计算机专业学生说这些!
java·c语言·数据结构·c++·python·学习·php
Dolphin_Home1 小时前
轻量实用的 XML 与 JSON / 对象互转工具类(Jackson 实现)
xml·java·json
Yeniden1 小时前
【设计模式】# 外观模式(Facade)大白话讲解!
java·设计模式·外观模式
脚踏实地的大梦想家1 小时前
【Go】P17 Go语言并发编程核心:深入理解 Goroutine (从入门到实战)
java·开发语言·golang
Yeniden1 小时前
【设计模式】 组合模式(Composite)大白话讲解
java·设计模式·组合模式
初学小白...1 小时前
线程同步机制及三大不安全案例
java·开发语言·jvm