vue导出表格

文章介绍了在Vue项目中使用iview的Upload组件实现表格导入功能,后端返回二进制流文件。通过设置responseType为blob来处理文件,利用FileReader读取内容,根据数据类型决定是解析JSON还是创建新的URL进行文件下载。在下载时,创建a标签触发点击下载文件。
摘要由CSDN通过智能技术生成

前言

vue实现导出表格,后端返回的是二进制流文件格式,前端如何处理然后导出表格。


此功能需要先导入表格,导入完成后会返回二进制流文件格式的表格去导出。
首先还是借助iview 的Upload 上传组件,以下是组件的一些属性设置:
format:支持的文件类型,on-format-error:文件格式验证失败时的钩子,action:上传的地址,before-upload:上传文件之前的钩子。

<Upload
  :format="['xls', 'xlsx', 'csv']"
  :on-format-error="handleGaodeFormatError"
  :show-upload-list="false"
  :action="''"
  :before-upload="handleUpload"
>
  <Button type="success" size="default" style="margin: 10px" :loading="uploadBtnLoading"
    >导出</Button
  >
</Upload>

在选择文件时验证,只能选择表格类型。

// 文件格式验证失败时的钩子
handleGaodeFormatError(file) {
  this.$Message.warning("选择文件格式错误,请选择Excel文件!");
},

借助上传文件之前的钩子,获取到上传的文件数据,设置return false,阻止自动上传。

handleUpload(file) {
   this.uploadBtnLoading = true;
   this.handleUploadModel(file);
   //阻止自动上传
   return false;
 },

在上传文件时,需要设置服务端返回的数据类型为responseType: “blob”。
New FileReader() 的使用
FileReader :读取文件内容
onloadend:文件读取完毕之后,不管成功还是失败触发
readAsText(): 读取文本文件,(可以使用Txt打开的文件)

// 导出失败原因
handleUploadModel(file) {
  let fileFormData = new FormData();
  fileFormData.append("file", file);
  const instance = axios.create({
    withCredentials: true,
  });
  instance({
    url: this.uploadGaodeExcel, // 上传地址
    method: "POST",
    data: fileFormData,
    responseType: "blob",
  }).then((res) => {
    // console.log(res,"res")
    const resData = res.data
    this.uploadBtnLoading = false;
    if (resData.type === 'application/json') {
      // 说明是普通对象数据,读取信息
      const fileReader = new FileReader()
      fileReader.onloadend = () => {
        const jsonData = JSON.parse(fileReader.result)
        // 后台信息
        // console.log(jsonData)
        if(jsonData.code != 200){ 
          return this.$Message.error(jsonData.message);
        }
      }
      fileReader.readAsText(resData)
    } else {
      // 下载文件  
      const blob = new Blob([resData], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
      const href = URL.createObjectURL(blob); // 创建新的URL表示指定的blob对象
      const a = document.createElement("a"); // 创建a标签
      a.style.display = "none";
      a.href = href; // 指定下载链接
      //设置指定元素上的某个属性值。如果属性已经存在,则更新该值
      a.setAttribute("download", "失败原因.xlsx");
      a.click(); // 触发下载
      URL.revokeObjectURL(a.href); // 释放URL对象
    }   
  })
},

这是上传完成后后端返回的二进制流文件数据。
在这里插入图片描述
这是设置了返回的数据类型responseType后拿到的数据,下载文件时的type应与此处的type类型保持一致。
在这里插入图片描述这样就可以下载成功啦!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值