Vue 实现导出功能及解决导出excel表格无法打开的问题

后台接口返回的数据:(文档流)
在这里插入图片描述
1.数据、文件格式全部在后台封装好,返回给前端一个链接,前端通过点击链接自动下载

window.location.href = '/api/xxx/xxx'。
window.open('/api/xxx/xxx?params')<a href={
    
    `/api/xxx/xxx?params`} download="报表.xlsx">导 出</a>

2.解析后台返回的文件流

这种方式就是后台将要导出的文件以文件流的方式返回给前端,前端通过blob去解析,再动态创建a标签。

封装单独的导出接口:

request.js

/**
 * get方法,对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 * * @param {Object} responseType [ 关键,不设置导出的文件无法打开]
 */
export function getBlob(url, params) {
    
    
  return new Promise((resolve, reject) => {
    
    
    axios
      .get(url, {
    
    
        params: params,
        responseType: "arraybuffer",
      })
      .then((res) => {
    
    
        resolve(res);
      })
      .catch((err) => {
    
    
        reject(err);
      });
  });
}

要在请求拦截器加上responseType = ‘arraybuffer’,必须设置,否则导出excel表格打不开

api.js

// 一键导出
export const exportUpload = (names) =>
  getBlob(`/defence/Defence/exportUpload?names=${
      
      names}`);

页面通过点击导出:

 // 一键导出
    async exportUpload() {
    
    
      // window.location = `/defence/Defence/exportUpload?names=${this.queryInfo.names}`;
      // let params = {
    
    
      //   names: this.queryInfo.names,
      // };
      // window.open(
      //   `http://172.16.1.120:8080/defence/Defence/exportUpload?names=${this.queryInfo.names}`
      // );
      // window.location.href = `/defence/Defence/exportUpload?names=${this.queryInfo.names}`;
      const res = await exportUpload(this.queryInfo.names);
      console.log(res.data);
      this.resolveBlob(res.data);
    },
    // 处理返回的数据格式
    resolveBlob(res) {
    
    
      const link = document.createElement("a");
      link.style.dispaly = "none";
      let binaryData = [];
      binaryData.push(res);
      link.href = window.URL.createObjectURL(new Blob(binaryData));
      // link.href = URL.createObjectURL(res);
      link.setAttribute("download", "装备数据.xlsx");
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },

猜你喜欢

转载自blog.csdn.net/WuqibuHuan/article/details/125442079
今日推荐