使用vue上传或下载excel文件

本文介绍了一个使用Vue.js实现的Excel文件导入和导出功能的示例。该示例展示了如何通过前端代码触发文件选择框来让用户上传Excel文件,并在后端进行处理。同时,也介绍了如何下载预设的Excel模板。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<form>
  <input type="file" name="fileup" id="uploadEventFile" v-on:change="fileChange($event)" style="display:none" />
</form>
<button v-on:click="importData($event)" class="imptbtn">导入excel</button>
<button v-on:click="download()" class="imptbtn">下载</button>
// 导入excel文件
importData: function(event) {
      event.preventDefault();
      $("#uploadEventFile").trigger("click")
    },
    fileChange: function (el) {
      el.preventDefault();//取消默认行为
      let vm = this
      let uploadEventFile = $("#uploadEventFile").val()
      this.file = el.target.files[0]
      if (uploadEventFile == '') {
       alert("请择excel,再上传");
      } else if (uploadEventFile.lastIndexOf(".xls") > 0 || uploadEventFile.lastIndexOf(".XLS") > 0) {
        let formData = new FormData();
        // 向 formData 对象中添加文件
        formData.append('file',this.file);
        let config = {
        // 一定要定义头
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }
        // url为对应的后端接口
        vm.$http.post(url,formData,config).then(function (response) {
         alert('上传成功')
        })
      } else {
        alert("只能上传excel文件");
      }
    },
    // 下载文件
    download: function(){
       axios({
            method: "get",
            url: "xxx",
            responseType: "arraybuffer"
          })
          .then(
            function(response) {
              let filename = "poiImport.xlsx";
              this.fileDownload(response.data, filename);
            }.bind(this)
          )
          .catch(
            function(error) {
              alert("网络请求出错");
            }.bind(this)
          );
    },
    fileDownload = function (data, fileName) {
      let blob = new Blob([data], {
        type: "application/octet-stream"
      });
      let filename = fileName || "filename.xls";
      if (typeof window.navigator.msSaveBlob !== "undefined") {
        window.navigator.msSaveBlob(blob, filename);
      } else {
        var blobURL = window.URL.createObjectURL(blob);
        var tempLink = document.createElement("a");
        tempLink.style.display = "none";
        tempLink.href = blobURL;
        tempLink.setAttribute("download", filename);
        if (typeof tempLink.download === "undefined") {
          tempLink.setAttribute("target", "_blank");
        }
        document.body.appendChild(tempLink);
        tempLink.click();
        document.body.removeChild(tempLink);
        window.URL.revokeObjectURL(blobURL);
      }
    };
Vue使用Element UI上传Excel文件通常是通过`el-upload`组件配合FileReader API来完成的。下面是一个简单的步骤描述: 1. 引入所需库:首先需要在项目中安装Element UI以及相关的依赖,如axios用于发送HTTP请求。 ```bash npm install element-ui axios ``` 2. 配置`el-upload`组件:在HTML模板中,创建一个`<el-upload>`元素,并设置一些属性,例如接受文件类型、最大大小等。同时,可以配置一个action(通常是一个API接收文件的地方),以及处理上传过程的方法。 ```html <el-upload class="upload-demo" action="/api/upload-excel" accept=".xlsx,.xls" max-size="5MB" :on-change="handleChange" :before-upload="beforeUpload" > <i class="el-icon-upload"></i> <div class="el-upload__text">点击上传</div> </el-upload> ``` 3. 定义处理函数:在Vue实例中定义`handleChange`和`beforeUpload`方法。`handleChange`会在用户选择文件后触发,而`beforeUpload`则可以在上传前做一些验证操作,比如读取文件内容预览。 ```javascript data() { return { file: null, }; }, methods: { handleChange(file) { this.file = file; }, beforeUpload(file) { // 判断是否是excel文件 const isExcel = /\.xls(\?.*)?|\.xlsx(\?.*)?$/.test(file.name); if (!isExcel) { this.$message.error('只支持上传Excel文件'); return false; // 返回false取消上传 } return true; // 返回true允许上传 }, uploadFile() { if (this.file) { axios.post(this.action, { file: this.file }, { onUploadProgress: event => { console.log(`百分比:${Math.round((event.loaded / event.total) * 100)}%`); }, }).then(response => { console.log(response.data); // 处理上传成功后的数据 }) .catch(error => { console.error('上传错误', error); }); } }, }, ``` 4. 用户交互:你可以提供一个“开始上传”按钮事件监听器,在用户点击时调用`uploadFile`方法。 注意:这个例子假设服务器端能够解析并处理上传Excel文件,实际开发时还要考虑后端接口的支持和文件解析的问题。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值