js中导入excel文件并转换为json格式的数据
选择的包为
xlsx
一个 js 库
测试结合 Vue + ElementUI一起使用。
先安装对应依赖
npm i xlsx —save
引入 elementUI 后,使用
upload
上传组件来实现文件导入<el-upload
ref="upload"
accept=".xls,.xlsx"
action=""
:auto-upload="false"
:on-change="handleUpload"
:show-file-list="false">
<el-button>EXCEL 导入</el-button>
编写读取
excel
文件的方法上传文件改变调用方法
methods: {
handleUpload (file) {
this.readExcel(file) // 如果在这里接收导出的 json 数据的话,会拿不到预期结果
}
}
导入excel文件为 json 格式
补充:
js 跳出循环使用 for of等
let test = []
for (let item of result) {
for (let i of Object.keys(item)) {
if (!formatCh.includes(i)) {
this.$message({ type: 'warning', message: `表头 “${ i}” 格式错误,请重新上传!` })
return false
}
}
// 数组对象替换对象的 key 值
test.push({
name: String(item.name),
unit: item.unit
})
}
还没有评论,来说两句吧...