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);
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM