Use axios en vue para descargar el fondo de Java y devolver el flujo de archivos para exportar el documento de Excel

Requisitos:
hay un botón de exportación encima de la tabla. Después de hacer clic, se llama a la interfaz de fondo y el flujo de datos se devuelve en segundo plano. Después de que la descarga sea exitosa, puede abrir Excel localmente.
inserte la descripción de la imagen aquí
inserte la descripción de la imagen aquí
Código:

<el-button type="primary" size="mini" icon="el-icon-download" @click="formatExportFile">金税格式数据导出</el-button>
import Storage from '@/utils/localStorage'
import ApiUrlconfig from '@/module/api/invoiceManage'
import axios from 'axios'
		formatExportFile () {
    
    
		  this.formatExportFileList(true,true)
		},
		setHeaders() {
    
    
          let loginInfo = Storage.get('loginInfo') || {
    
    }
          console.log('loginInfo', loginInfo);
          let headers = {
    
    }
          headers['X-Store'] = JSON.stringify({
    
    storeSysNo: loginInfo.StoreSysNo, storeNo: loginInfo.StoreNO})
          headers['Authorization'] = `${
      
      loginInfo.token_type} ${
      
      loginInfo.access_token}`
          headers['Content-Type'] = 'application/json;charset=UTF-8'
          return headers
        },
        async formatExportFileList(research, isExport=false) {
    
    
          this.loading = true
          let pageSize=isExport? 0 :this.pageSize
          // 这里的参数和列表请求参数一致
          let params = {
    
    
            // accountSetCode:this.accountSet,
            pageSize: pageSize,
          };
          if (research && !isExport) {
    
    
            // 重新搜索
            this.currentPage = 1
          }
          params.pageNum = isExport? 1 :this.currentPage
          if (this.accountSet.length != 0) {
    
    
              params.accountSet = this.accountSet;
          }
          if (this.searchForm.fphm.length != 0) {
    
    
            params.fphm = this.searchForm.fphm;
          }
          if (this.searchForm.custName.length != 0) {
    
    
            params.custName = this.searchForm.custName;
          }
          if (this.searchForm.invType.length != 0) {
    
    
            params.invType = this.searchForm.invType;
          }
          if (this.searchForm.orderNo.length != 0) {
    
    
            params.orderNo = this.searchForm.orderNo;
          }
          if (this.searchForm.dateType.length != 0) {
    
    
            params.dateType = this.searchForm.dateType;
          }
          if (this.searchForm.invoiceFrom.length != 0) {
    
    
            params.invoiceFrom = this.searchForm.invoiceFrom;
          }
          if (typeof (this.searchForm.startDate) != "undefined" && this.searchForm.startDate!=null && this.searchForm.startDate!='') {
    
    
            params.startDate =this.searchForm.startDate + " 00:00:00";
          }
          if (typeof (this.searchForm.endDate) != "undefined" && this.searchForm.endDate!=null && this.searchForm.endDate!='') {
    
    
            params.endDate = this.searchForm.endDate + " 23:59:59";
          }
          if(typeof params.endDate !="undefined" && typeof params.startDate !="undefined" && (new Date(params.endDate.replace(/-/g,"/"))).getTime()<(new Date(params.startDate.replace(/-/g,"/"))).getTime()) {
    
    
            this.$tip.notify("结束日期小于开始日期","warning")
            return;
          }
          // 通过axios调用接口
          await axios({
    
    
            method: 'POST',
            url: ApiUrlconfig.getReMakeInvoice,
            responseType: 'blob',
            headers: this.setHeaders(),
            data: params
          }).then(res => {
    
    
            console.log('res', res)
            if (!res.msg) {
    
    
              this.exportLoading = false
              // 这里根据后端返回使用res或res.data
              var blob = new Blob([res], {
    
    type: 'application/ms-excel'});
              var elink = document.createElement('a');
              elink.download = '销项发票管理' + '.xlsx';
              elink.href = URL.createObjectURL(blob);
              document.body.appendChild(elink);
              elink.click(); //点击下载
              document.body.removeChild(elink); //下载完成移除元素
              window.URL.revokeObjectURL(elink); //释放掉blob对象
              this.loading = false
              return
            }
            throw new Error(res.msg)
          }).catch(err => {
    
    
            this.loading = false
            this.$notify.error({
    
    
              title: '提示',
              message: err.message
            })
          })
        },

Artículo de referencia:
use axios en vue para descargar el fondo de Java y devolver el flujo de archivos para exportar el documento de Excel

Cuando el front-end llama a la interfaz para exportar el archivo de Excel, la respuesta en la red en la herramienta de desarrollo del navegador tiene un valor de retorno pero caracteres ilegibles, y el valor de retorno de axios empaquetado por sí mismo no está definido

Supongo que te gusta

Origin blog.csdn.net/guairena/article/details/123177742
Recomendado
Clasificación