#template <template> <div> <input type="file" id="files" ref="upload" accept=".xls,.xlsx" style="display: none"> <el-button slot="trigger" type="warning" @click="clickLoad" style="margin-right: 20px">从Excel加载</el-button> </div> </template> methods(){ clickLoad() { this.$refs.upload.dispatchEvent(new MouseEvent('click')) }, readExcel(e) {//表格导入 let that = this; const files = e.target.files; let validRule = /\.(xls|xlsx)$/ if (files.length <= 0) {//如果没有文件名 return false; } else if (!validRule.test(files[0].name.toLowerCase())) { this.$Message.error('上传格式不正确,请上传xls或者xlsx格式'); return false; } const fileReader = new FileReader(); fileReader.onload = (e) => { try { const data = e.target.result; const workData = XLSX.read(data, { type: 'binary' }); // console.log(workData)// 文件的内容 const wsName = workData.SheetNames[0];//取第一张表 const ws = XLSX.utils.sheet_to_json(workData.Sheets[wsName]);//生成json表格内容 // console.log(ws); //自第二行开始的内容 //{ 这里可以做相应的处理 } //{ 这里可以做相应的处理 } // console.log("table:", this.tablesData) for (let i = 0; i < this.tablesData.length; i++) { let item = this.tablesData[i] let allKey = Object.keys(item) for (let j = 0; j < ws.length; j++) { let item2 = ws[j] let key1 = item['a'] + "_" + item['b'] + "_" + item['c'] let key2 = item2['a'] + "_" + item2['b'] + "_" + item2['c'] if (key1 === key2) { for (let key of allKey) { //只对20开头的key做值更新 if (key.indexOf("20") === 0) { console.log("key1:", key1, "key2:", key2, "key:", key, "value:", item2[key]) this.$set(this.tablesData[i], key, item2[key]) } } } } } this.$refs.upload.value = ''; // 处理完成 清空表单值 } catch (e) { this.$message.error("解析表格失败") return false; } }; fileReader.readAsBinaryString(files[0]); } }, mounted(){ //注册事件 this.$refs.upload.addEventListener('change', e => { this.readExcel(e) }) }