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>
相关推荐
NGC_66111 分钟前
ConcurrentHashMap介绍
java·开发语言
JY.yuyu3 分钟前
Java Web上架流程(Nginx反向代理+负载均衡 ,Apache配置,Maven安装打包,Tomcat配置)
java·开发语言·前端
逸Y 仙X12 分钟前
文章十二:索引数据的写入和删除
java·大数据·spring boot·spring·elasticsearch·搜索引擎·全文检索
代码探秘者16 分钟前
【算法篇】5.链表
java·数据结构·人工智能·python·算法·spring·链表
1104.北光c°18 分钟前
Leetcode3.无重复字符的最长子串 HashSet+HashMap 【hot100算法个人笔记】【java写法】
java·开发语言·笔记·程序人生·算法·leetcode·滑动窗口
Binary-Jeff18 分钟前
Maven 依赖作用域详解:compile、provided、runtime、test
java·spring·spring cloud·servlet·java-ee·maven
QH_ShareHub20 分钟前
Rstudio 与 R 打开 Rdata (压缩文件) 差异
java·前端·r语言
spencer_tseng20 分钟前
apache-maven-3.9.6
java·maven
yashuk26 分钟前
springboot与springcloud对应版本
java·spring boot·spring cloud
strayCat2325527 分钟前
4. Spring Boot 数据持久化(JPA)
java·spring boot·后端