• 下载工程resources目录下的模板excel文件


    一、添加依赖

    1. <dependency>
    2. <groupId>org.apache.poi</groupId>
    3. <artifactId>poi-ooxml</artifactId>
    4. <version>5.1.0</version>
    5. </dependency>

    二、编写接口

    1. @GetMapping("/downloadTemplate")
    2.     public void downloadTemplate(HttpServletRequest request,
    3.                                  HttpServletResponse response){
    4.         String fileName = "template"+File.separator+"字段标准导入模板.xlsx";
    5.         InputStream is = ClassLoader.getSystemResourceAsStream(fileName);
    6.         response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    7.         response.setCharacterEncoding("utf-8");
    8.         Workbook wb = null;
    9.         try {
    10.             wb = new XSSFWorkbook(is);
    11.         } catch (IOException e) {
    12.             throw new RuntimeException(e);
    13.         }
    14.         try {
    15.             wb.write(response.getOutputStream());
    16.         } catch (Exception e) {
    17.             log.error("下载导入模板异常{}", e.getMessage());
    18.         } finally {
    19.             IOUtils.closeQuietly(wb);
    20.             if(is!=null){
    21.                 try {
    22.                     is.close();
    23.                 } catch (IOException e) {
    24.                     throw new RuntimeException(e);
    25.                 }
    26.             }
    27.         }
    28.     }


    三、这种代码,在windows上调试没问题,打成jar包发到linux环境上会有问题,改成如下代码就行:

    1. @GetMapping("/downloadTemplate")
    2.     public void downloadTemplate(HttpServletRequest request,
    3.                                  HttpServletResponse response){
    4.         String fileName = "template"+File.separator+"ColumnStandardImportTemplate.xlsx";
    5.         response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    6.         response.setCharacterEncoding("utf-8");
    7.         try (InputStream is = new ClassPathResource(fileName).getInputStream();
    8.              Workbook wb = new XSSFWorkbook(is);
    9.              ServletOutputStream os = response.getOutputStream()) {
    10.             wb.write(os);
    11.             os.flush();
    12.         } catch (Exception e) {
    13.             log.error("下载导入模板异常", e);
    14.         }
    15.     }


        

  • 相关阅读:
    Java+JSP+MySQL基于SSM的在线投票系统-计算机毕业设计
    基于STM32结合CubeMX学习Free-RT-OS的源码之任务调度
    橘猫去水印小程序源码(可自定义解析接口、后端使用PHP)
    javascript 使用setInterval模拟计算程序读秒
    Nginx(七) root和alias的区别及详细测试
    go语言输出带颜色字体
    POWER SOURCE ETA埃塔电源维修FHG24SX-U概述
    【多式联运】基于帝国企鹅算法、遗传算法、粒子群算法求解多式联运路径优化问题附matlab代码
    Sky Computing
    【Rust 日报】2022-06-19 Rust 1.63 新特性令人期待
  • 原文地址:https://blog.csdn.net/heming20122012/article/details/139781743