# 安装依赖
npm install xlsx |
# 引入
import XLSX from 'xlsx' |
# 第一种 input 通常方式
template 中加入 input
<input type="file" ref="upload" accept=".xls,.xlsx" class="outputlist_upload"> |
data 中声明变量
data() { | |
return { | |
outputs: [] | |
} | |
}, |
mounted 中绑定事件
mounted() { | |
this.$refs.upload.addEventListener('change', e => {//绑定监听表格导入事件 | |
this.readExcel(e); | |
}) | |
}, |
调用主函数
readExcel(e) {//表格导入 | |
var that = this; | |
const files = e.target.files; | |
console.log(files); | |
if(files.length<=0){//如果没有文件名 | |
return false; | |
}else if(!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())){ | |
this.$Message.error('上传格式不正确,请上传xls或者xlsx格式'); | |
return false; | |
} | |
const fileReader = new FileReader(); | |
fileReader.onload = (ev) => { | |
try { | |
const data = ev.target.result; | |
const workbook = XLSX.read(data, { | |
type: 'binary' | |
}); | |
const wsname = workbook.SheetNames[0];//取第一张表 | |
const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]);//生成json表格内容 | |
console.log(ws); | |
that.outputs = [];//清空接收数据 | |
//编辑数据 | |
for(var i= 0;i<ws.length;i++){ | |
var sheetData = { | |
address: ws[i].addr, | |
value: ws[i].value | |
} | |
that.outputs.push(sheetData); | |
} | |
this.$refs.upload.value = ''; | |
} catch (e) { | |
return false; | |
} | |
}; | |
fileReader.readAsBinaryString(files[0]); | |
} |
# 第二种结合 element UI 的 upload 控件实现读取文件并生成数组
upload 绑定函数
upload(file,fileList){ | |
console.log("file",file); | |
console.log("fileList",fileList); | |
let files = {0:file.raw} | |
this.readExcel1(files); | |
} |
readExcel1 主函数
readExcel1(files) {//表格导入 | |
var that = this; | |
console.log(files); | |
if(files.length<=0){//如果没有文件名 | |
return false; | |
}else if(!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())){ | |
this.$Message.error('上传格式不正确,请上传xls或者xlsx格式'); | |
return false; | |
} | |
const fileReader = new FileReader(); | |
fileReader.onload = (ev) => { | |
try { | |
const data = ev.target.result; | |
const workbook = XLSX.read(data, { | |
type: 'binary' | |
}); | |
const wsname = workbook.SheetNames[0];//取第一张表 | |
const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]);//生成json表格内容 | |
console.log(ws); | |
// that.peopleArr = [];//清空接收数据 | |
// if(that.peopleArr.length == 1 && that.peopleArr[0].roleName == "" && that.peopleArr[0].enLine == ""){ | |
// that.peopleArr = []; | |
// } | |
//重写数据 | |
try{ | |
}catch(err){ | |
console.log(err) | |
} | |
this.$refs.upload.value = ''; | |
} catch (e) { | |
return false; | |
} | |
}; | |
fileReader.readAsBinaryString(files[0]); | |
}, |