js中导入excel文件并转换为json格式的数据

╰半橙微兮° 2022-09-01 14:45 320阅读 0赞

选择的包为 xlsx一个 js 库

测试结合 Vue + ElementUI一起使用。

  • 先安装对应依赖

    npm i xlsx —save

  • 引入 elementUI 后,使用 upload 上传组件来实现文件导入

    <el-upload

    1. ref="upload"
    2. accept=".xls,.xlsx"
    3. action=""
    4. :auto-upload="false"
    5. :on-change="handleUpload"
    6. :show-file-list="false">
    7. <el-button>EXCEL 导入</el-button>

  • 编写读取 excel 文件的方法

  • 上传文件改变调用方法

    methods: {

    1. handleUpload (file) {
    2. this.readExcel(file) // 如果在这里接收导出的 json 数据的话,会拿不到预期结果
    3. }

    }

导入excel文件为 json 格式
在这里插入图片描述
补充:
js 跳出循环使用 for of等

  1. let test = []
  2. for (let item of result) {
  3. for (let i of Object.keys(item)) {
  4. if (!formatCh.includes(i)) {
  5. this.$message({ type: 'warning', message: `表头 “${ i}” 格式错误,请重新上传!` })
  6. return false
  7. }
  8. }
  9. // 数组对象替换对象的 key 值
  10. test.push({
  11. name: String(item.name),
  12. unit: item.unit
  13. })
  14. }

发表评论

表情:
评论列表 (有 0 条评论,320人围观)

还没有评论,来说两句吧...

相关阅读