java poi批量导出excel模板并打包成ZIP压缩文件

文章目录

  • 前言
    • 1、controller
    • 2、service
    • 3、业务层
    • 工具接口
    • vue页面及接口
  • 总结


前言

java poi批量导出excel模板并打包成ZIP压缩文件

1、controller

代码如下(示例):

/**
  *导出质量检测模板
  * @params [response, po]
  * @return {@link AjaxJson}
  * @throws GlobalException 自定义异常
  * @author zlb
  * @date 2022/3/17
  */
  @RequestMapping("/downTemplateQualityInspect")
  public AjaxJson downTemplateQualityInspect(HttpServletResponse response, @RequestBody QualityInspectPo po)throws GlobalException {
    return iBdReMortarService.downTemplateQualityInspect(response, po);
  }

2、service

代码如下(示例):

/**
   *导出质量检测模板
   * @params [response, po]
   * @return {@link AjaxJson}
   * @throws GlobalException 自定义异常
   * @author zlb
   * @date 2022/3/17
   */
  AjaxJson downTemplateQualityInspect(HttpServletResponse response, QualityInspectPo po)throws GlobalException;

3、业务层


 /**
   * 导出质量检测模板
   *
   * @return {@link AjaxJson}
   * @throws GlobalException 自定义异常
   * @params [response, po]
   * @author zlb
   * @date 2022/3/17
   */
  @Override
  public AjaxJson downTemplateQualityInspect(HttpServletResponse response, QualityInspectPo po) throws GlobalException {
    try {
      if (StringUtil.isNotEmpty (po.getDownCheckedStr ())) {
        List<String> list = JSON.parseArray (po.getDownCheckedStr (), String.class);
        //先将有数据导出的与现有不需要导出数据的模板导出分开,后期统一后在修改成统一的一个模板导出方法
        if (list.size () > 0) {
          // 将excel导出的文件位置
          HashMap<String, ByteArrayOutputStream> fileHashMap = new HashMap<> (20);
          for (String modelName : list) {
            File file = ResourceUtils.getFile ("classpath:template/qualityInspect/" + modelName + ".xlsx");
            ByteArrayOutputStream byteArrayOutputStream = null;
            switch (modelName) {
              case "质量检测原材料":
                byteArrayOutputStream = exportExcelDataOne (file, po);
                break;
                case "质量检测实体质量":
                  byteArrayOutputStream = exportExcelDataOne (file, po);
                  break;
                case "质量检测砂浆混凝土":
                  byteArrayOutputStream = exportExcelDataOne (file, po);
                  break;
                case "质量检测中间产品":
                  byteArrayOutputStream = exportExcelDataOne (file, po);
                  break;
              default:
            }
            fileHashMap.put (modelName + ".xlsx", byteArrayOutputStream);
          }

          if (fileHashMap.size () > 0) {
            byte[] b = FileUtils.compressExportExcelFileZip (fileHashMap);
            if (b != null && b.length > 0) {
              ServletOutputStream outputStream = response.getOutputStream ();
              outputStream.write (b);
              outputStream.flush ();
              outputStream.close ();
            }
          }

        }
      }
    } catch (Exception e) {
      e.printStackTrace ();
      throw new GlobalException (e.getMessage ());
    }
    return null;
  }
   private ByteArrayOutputStream exportExcelDataOne(File file, QualityInspectPo po) {
    try {
      if (file.exists ()) {
        //处理导出数据
        List<Object> list = new ArrayList<> ();
        return FileUtils.xlsxOutput (file, list);
      }
    } catch (Exception e) {
      e.printStackTrace ();
      throw new GlobalException (e.getMessage ());
    }
    return null;
  }

工具接口

    /**
   * 使用XSSFWorkbook导出excel文件
   * @param file 模板源文件
   * @param list  导出数据
   * @return 文件的数组输出流对象
   * @throws IOException
   * @throws IOException
   */
  public static ByteArrayOutputStream xlsxOutput(File file, List<Object> list) throws IOException,
      InvalidFormatException {
    if (file != null) {
      XSSFWorkbook sheets = new XSSFWorkbook (file);
      ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
      sheets.write (byteArrayOutputStream);
      if (byteArrayOutputStream.size() > 0) {
        return byteArrayOutputStream;
      }
      byteArrayOutputStream.flush();
      byteArrayOutputStream.close();
    }
    return null;
  }
  
  /**
   * 批量压缩需要导出文件
   * @throws IOException
   * @params [fileMap]  文件名称,导出后的数组输入流
   * @author zY
   * @date 2022/03/22
   */
  public static byte[] compressExportExcelFileZip(HashMap<String, ByteArrayOutputStream> fileMap) throws IOException {
    if (fileMap.size() > 0) {
      Set<String> mapKey = fileMap.keySet();
      ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
      ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream);
      for (String fileName : mapKey) {
        ByteArrayOutputStream exportFileByteArray = fileMap.get(fileName);
        if (exportFileByteArray.size() > 0) {
          zipOutputStream.putNextEntry(new ZipEntry(fileName));
          zipOutputStream.write(exportFileByteArray.toByteArray());
          zipOutputStream.closeEntry();
        }
      }
      byteArrayOutputStream.flush();
      zipOutputStream.flush();
      zipOutputStream.close();
      byteArrayOutputStream.close();
      return byteArrayOutputStream.toByteArray();
    }
    return null;
  }

vue页面及接口

<!--模板下载弹窗区域-->
    <el-dialog title="导出" :visible.sync="exportVisiable" @close="closeDownLog" width="30%">
      <div >
        <div class="downRow">
          <el-checkbox v-model="template01" true-label="质量检测原材料">质量检测原材料</el-checkbox>
        </div>
        <div class="downRow">
          <el-checkbox v-model="template02" true-label="质量检测实体质量">质量检测实体质量</el-checkbox>
        </div>
        <div class="downRow">
          <el-checkbox v-model="template03" true-label="质量检测砂浆混凝土">质量检测砂浆混凝土</el-checkbox>
        </div>
        <div class="downRow">
          <el-checkbox v-model="template04" true-label="质量检测中间产品">质量检测中间产品</el-checkbox>
        </div>
      </div>
      <span slot="footer" class="dialog-foolter">
       <el-button @click="closeDownLog">取 消</el-button>
        <el-button type="primary" @click="startDown">确 认</el-button>
      </span>
    </el-dialog>
    
       closeDownLog() {
        this.exportVisiable = false;
        this.template01 = "undefined";
        this.template02 = "undefined";
        this.template03 = "undefined";
        this.template04 = "undefined";
      },
      startDown() {
        let checkedList = [];
        let checkList = ["template01", "template02", "template03", "template04"];
        for (let i = 0; i < checkList.length; i++) {
          let a = this[checkList[i]];
          let ch = this[checkList[i]];
          if (ch && ch !== "undefined") {
            checkedList.push(ch);
          }
        }
        if (checkedList.length === 0) {
          this.$message.warning("当前无模板文件导出!");
          return;
        }
        let temps = this.temp;
        let data = {};
        data.downCheckedStr = JSON.stringify(checkedList);
        downTemplateQualityInspect(data).then(resp => {
          if (resp.status === 200 && resp.data.type !== "application/json") {
            let blob = new Blob([resp.data], { type: "application/zip" });
            let url = URL.createObjectURL(blob);
            let $a = document.createElement("a");
            $a.setAttribute("href", url);
            $a.setAttribute("download", "模板文件.zip");
            $a.click();
            URL.revokeObjectURL(url);
          } else {
            this.$message.warning("无法获取模板文件!");
          }
        })
      },

总结

提示:这里仅导出空模板,如需添加导出数据 ,自行处理。
//处理导出数据
List list = new ArrayList<> ();

你可能感兴趣的:(编译工具,idea,java,java,intellij-idea,javascript,vue.js,后端)