vue表格数据导入

1、安装依赖

npm install xlsx -S

2、在vue组件中引入

import * as XLSX from 'xlsx' // 引入数据导入插件

3、template代码,结合element上传组件

 <el-upload
   action=''
   class="upload"
   accept=".xlsx,.xls"
   :auto-upload="false"
   :show-file-list="false"
   :on-change="importData"
   >
     <el-button type="primary" size="small">导入数据</el-button>
 </el-upload>

4、script代码

data () {
    return {
      tableData: []
    }
  },
  methods: {
    /**
    * @description: 导入列表数据
    * @param {object} file 要上传的文件
    */
    importData (file) { // 定义函数importData,参数为file,表示要上传的文件
      const types = file.name.slice(file.name.lastIndexOf('.')) // 获取文件后缀名
      const fileType = ['.xlsx', '.xls'].some((item) => item === types) // 判断文件类型是否为xlsx或xls
      if (!fileType) { // 如果文件类型不正确,提示用户重新上传
        this.$message.warning('文件格式错误!请重新上传')
        return // 如果文件类型不正确 结束函数
      }
      this.tableData = [] // 初始化tableData,用于存储读取到的数据
      const reader = new FileReader() // 创建文件读取器
      reader.readAsBinaryString(file.raw) // 将文件内容读取成二进制字符串
      reader.onload = () => { // 当文件读取成功时执行以下操作
        const binary = reader.result // 获取文件内容的二进制字符串
        const wb = XLSX.read(binary, { // 将二进制字符串转换成workbook对象
          type: 'binary'
        })
        // 将workbook对象中的第一个sheet转换成JSON格式
        const outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])
        console.log(outdata)        
      }
    },
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值