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>
相关推荐
小锋java12343 分钟前
【技术专题】Matplotlib3 Python 数据可视化 - Matplotlib3 绘制饼状图(Pie)
java
wuminyu4 分钟前
专家视角看JVM_StartThread
java·linux·c语言·jvm·c++
专职5 分钟前
cursor中与vim插件冲突时的配置
编辑器·vim·excel
awljwlj11 分钟前
黑马点评复习—缓存相关【包含可能的问题和基础知识复习】
java·后端·spring·缓存
Gofarlic_OMS11 分钟前
ENOVIA基于Token的许可证消费模式分析与分点策略
java·大数据·开发语言·人工智能·制造
ROLL.717 分钟前
Git和Repo
java·git·安卓
小雅痞26 分钟前
[Java][Leetcode simple] 1. 两数之和
java·算法·leetcode
bingd0126 分钟前
慕课网、CSDN、菜鸟教程…2026 国内编程学习平台实测对比
java·开发语言·人工智能·python·学习
大飞哥~BigFei29 分钟前
缓存一致性终极解决方案之Facebook租约机制的开源实现集成改造
java·缓存·开源
凌冰_33 分钟前
Thymeleaf 核心语法详解
java·前端·javascript