• java 从resource下载excel打不开


    1. @GetMapping("/download/template")
    2. public void template(HttpServletResponse response) throws IOException {
    3. ServletOutputStream outputStream = response.getOutputStream();
    4. InputStream inputStream = null;
    5. try {
    6. //从resource获取excel文件流
    7. inputStream = getClass().getClassLoader().getResourceAsStream("批量上传产品模板.xlsx");
    8. String fileName = "批量上传产品模板.xlsx";
    9. response.reset();
    10. response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    11. response.setCharacterEncoding("UTF-8");
    12. response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
    13. response.setHeader("Content-Length", String.valueOf(inputStream.available()));
    14. IoUtil.copy(inputStream, outputStream);
    15. } catch (Exception e) {
    16. e.printStackTrace();
    17. throw new ServiceException("下载失败");
    18. } finally {
    19. inputStream.close();
    20. outputStream.flush();
    21. outputStream.close();
    22. }
    23. }

    由于Java项目在编译/Maven打包Excel等资源文件时,使用了Maven的filter,导致打包后的Excel文件乱码或者损坏。

    需要再maven添加插件

    1. <build>
    2. <plugins>
    3. <plugin>
    4. <groupId>org.apache.maven.pluginsgroupId>
    5. <artifactId>maven-resources-pluginartifactId>
    6. <configuration>
    7. <encoding>UTF-8encoding>
    8. <nonFilteredFileExtensions>
    9. <nonFilteredFileExtension>xlsxnonFilteredFileExtension>
    10. <nonFilteredFileExtension>xlsnonFilteredFileExtension>
    11. nonFilteredFileExtensions>
    12. configuration>
    13. plugin>
    14. plugins>
    15. <resources>
    16. <resource>
    17. <directory>src/main/resourcesdirectory>
    18. <filtering>truefiltering>
    19. resource>
    20. resources>
    21. build>

  • 相关阅读:
    三季度现货白银基本面分析
    聊聊 RPA 方向的规划:简单有价值的事情长期坚持做
    关键短语提取的典型方法
    PAC工单科目金额明细
    locust 权重
    并查集理解与应用(详细版)
    Hadoop3教程(三十):(生产调优篇)纠删码
    OX08B40sensor的规格书
    Unity实现跨场景的传送门
    忘记mysql密码后如何修改密码(2022最新版详细教程保姆级)
  • 原文地址:https://blog.csdn.net/m0_47104939/article/details/132617539