前端导入Excel表格数据

在诸如ERP管理系统,有些需求需要使用Excel的数据。

首先,在项目中安装 xlsx 模块

npm install xlsx --save

使用input的file属性,并定义事件

<template>
  <div>
     <!-- 如需让导入的文件名隐藏
    <div style="height: 0;overflow: hidden;">
      <input type="file" @change="handleChange($event.target.files[0])" id="selectedFile">
    </div>
    <input type="button" value="Browse..." onclick="document.getElementById('selectedFile').click();" /> -->

   <input type="file" @change="handleChange($event.target.files[0])" id="selectedFile">
  </div>
</template>

项目中正确引用xlsx模块

import * as XLSX from 'xlsx';

事件函数部分:

 handleChange(file) {
      const reader = new FileReader();
      reader.onload = () => {
        const workbook = XLSX.read(reader.result, { type: 'binary' });
        console.log(workbook);
        const sheet = workbook.Sheets[workbook.SheetNames[0]]
        const data = XLSX.utils.sheet_to_json(sheet, { header: 1 })
        console.log(data); //此处已经拿到处理过后的数据data,任由开发者使用
        // 例如把提取的数据以对象的形式导入到数组中,供table使用
        this.tableData = data.slice(1).map((item) => {
          return { id: item[0], name: item[1], }
        })
      };
      if (file instanceof File) {
        reader.readAsBinaryString(file);
      } else if (file instanceof Blob) {
        reader.readAsBinaryString(new File([file], file.name));
      }
    },

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值