【Vue】vue+elementui+axios之excel的导入导出功能

599 阅读1分钟

1.导入功能:

<el-upload
class="btn btn-info btn-sm leadingIn"
action
accept=".csv,
 application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,
 application/vnd.ms-excel"
:http-request="uploadExcelDetail"
multiple
:limit="1"
ref='upload'
:file-list='excelList'>
      <el-button size="small" type="primary">导入</el-button>
</el-upload>

实现方法

export default {  
  data: function() {
     return {
       excelList: [],
       user_id: localStorage.getItem("userId"),
     }
  },
  methods: {
    // 导入Excel
    uploadExcelDetail(item) {
    let that = this;
    const form = new FormData();
    form.append("file", item.file);
    form.append("userId", that.user_id);
    axios({ 
        method: "post",
        url: "url,
        data: form
    }).then(function(res) {
          if (res.data.code == "0000") {
            that.$message({
              type: "success",
              message: res.data.msg
            });
            that.findDetailList()
          } else {
            that.$message({ 
              type: "info",
              message: res.data.msg
            });
          }
     }).catch(error => {
          loading.close();
          console.log(error);
     });
   }
  }
}

2.导出功能:

<el-button 
class="btn btn-success btn-sm" 
type="text" 
@click="leadingOut()">导出</el-button>

实现方法

export default {
  data: function() {
    return {
      user_token: localStorage.getItem("token")
    }
  },
  methods: {
    // 导出
    leadingOut: function() {
      let that = this;
      window.URL = window.URL || window.webkitURL;
      axios({
        method: "post",
        url: "url",
        responseType: "blob",
        data: {
          user_token: that.user_token,
        }
      }).then(res => {
          let blob = new Blob([res.data], { type: "application/vnd.ms-excel" });
          const link = document.createElement("a");
          link.href = window.URL.createObjectURL(blob);
          link.download = "***.xlsx";
          link.click();
          window.URL.revokeObjectURL(link.href);
      }).catch(error => {
          console.log(error);
      });
    }
  }
}