Vue + axios + SpringBoot 2实现导出Excel

Vue + axios + SpringBoot 2实现导出Excel

1. 前端js代码-发送Http请求

   

/**
   * 文件下载
   * @param url 下载地址
   * @param fileName 文件名称
   * @param params 参数
   */
  downloadFile: function (url, params) {
    params = params || {}
    let httpService = axios.create({
      timeout: 300000, // 请求超时时间
      headers: {
        'Cache-Control': 'no-cache'
      }
    })
    return httpService({
      method: 'POST',
      url:  url,
      data: params,
      responseType: 'blob'
    }).then(res => {
      return res.data
    })
  },
  /**
   *文件上传
   * @param url 上传地址
   * @param file 文件对象   target.files <input type='file'> 的文件对象
   * @param params 参数可以添加fileName ,type等等
   * @returns {Promise<AxiosResponse | never>}
   */
  uploadFile: function (url, file, params) {
    const formData = new FormData()
    params = params || {}
    Object.keys(params).map(key => {
      formData.append(key, params[key])
    })
    formData.append('type', params['type'] || 'ReadExcel')
    formData.append(params['fileName'] || 'file', file)
    let httpService = axios.create({
      timeout: 300000, // 请求超时时间
      headers: {
        'Cache-Control': 'no-cache',
        'Content-Type': 'multipart/form-data'
      }
    })
    return httpService.post( url, formData).then(res => {
      return res.data
    })
  }

 

2. 前端js代码-处理后端返回的流数据(通用处理二进制文件的方法,而不仅仅针对Excel)

/**
 @resData  后端响应的流数据
 @fileName 文件名称 如果后端设置的是xls/xlsx与后端文件后缀一致。
**/
 function dealDownLoadData(resData,fileName){
   try {

        let blob ;
        if(resData instanceof Blob){
          blob = resData;
        }else{
          blob = new Blob([resData], { type: resData.type});
        }
        if (!!window.ActiveXObject || "ActiveXObject" in window) {  //IE浏览器
                //navigator.msSaveBlob(blob, fileName);   //只有保存按钮
                navigator.msSaveOrOpenBlob(blob, fileName); //有保存和打开按钮 
        }else{
                var linkElement = document.createElement('a');
                var url = window.URL.createObjectURL(blob);
                linkElement.setAttribute('href', url);
                linkElement.setAttribute("download", fileName);
                var clickEvent = new MouseEvent("click", 
                    {
                      "view": window,
                      "bubbles": true,
                      "cancelable": false
                    });
                 linkElement.dispatchEvent(clickEvent);
        }
    } catch (ex) {
        console.log(ex);
    }

}

3.导出Excel

/**
     * 导出Excel
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/xxx")
    public ResponseEntity<Resource> downloadFileApi() throws Exception {
        //Excel场景一:直接创建,然后编辑内容
        HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
        
        //Excel场景二:读取模板,然后在模板中编辑内容
        POIFSFileSystem poifsFileSystem = new POIFSFileSystem(new FileInputStream("/template.xls"));
        hssfWorkbook = new HSSFWorkbook(poifsFileSystem);
        
        //写到输出流中
        ByteArrayOutputStream  outputStream = new  ByteArrayOutputStream();
        hssfWorkbook.write(outputStream);
        //文件名称:注意:这里的后缀名称必须是xls或 xlsx,不然不能识别为excel
        String fileName = "xxx.xls";
        //返回
        ByteArrayInputStream is = new ByteArrayInputStream(outputStream.toByteArray());
        //调用通用下载文件方法
        return this.downloadFile(is, fileName);
          
    }

 

 

/**
     * 通用的下载方法,可以下载任何类型文件
     * @param is
     * @param fileName
     * @return
     * @throws IOException
     */
    public  ResponseEntity<Resource> downloadFile(InputStream is,String fileName) throws IOException{
        
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        headers.add("charset", "utf-8");
        //设置下载文件名
        headers.add("Content-Disposition", "attachment;filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"");
        Resource resource = new InputStreamResource(is);
        return ResponseEntity.ok()
                .headers(headers)
                //根据文件名称确定文件类型。
                .contentType(MediaType.parseMediaType(HttpKit.getMimeType(fileName)))
                .body(resource);
    }

 

posted @ 2020-07-28 14:02  ~风铃~  阅读(872)  评论(0编辑  收藏  举报