使用的是ant-design-vue 的ui
封装好的代码:
<template> <div> <a-button type="primary" @click="btnImportClick" size="small" style="margin: 0 10px">{{ text }}</a-button> <input ref="upload" @change="readExcel($event)" type="file" accept=".xls,.xlsx" style="display:none;"> </div> </template> <script> import XLSX from 'xlsx' // import { read, utils } from 'xlsx' export default { name:'ImportExcel', data() { return { outputs:[] } }, props:{ text:{ type:String, default: '导入' } }, mounted() { // this.$refs.upload.addEventListener('change', e => {//绑定监听表格导入事件 // this.readExcel(e) // }) }, methods: { async btnImportClick(){ this.$refs.upload.click() this.$emit('getExcelMsg', await this.outputs) }, // sendMsg(){ // this.$emit('getExcelMsg', this.outputs) // }, async 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表格内容 // that.outputs = []//清空接收数据 if(that.outputs.length != 0) { 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]) // ----这里就是为空 } }, watch:{ outputs:{ handler: function(oldVal, newVal){ } } } } </script> <style> </style>
在其他页面调用:
<import-excel @getExcelMsg="getExcelData"></import-excel>
methods: { // 获取excel的值 getExcelData(data){ console.log('///',data) this.importData = data // console.log('---------', this.importData) },
}