template中的内容
<a-upload
name="file"
:multiple="true"
:beforeUpload="beforeUpload"
accept=".xlsx, .xls"
@change="handleChange"
>
<a-button> <a-icon type="upload" /> 点击上传 </a-button>
</a-upload>
methods代码
// 修改上传的状态
beforeUpload (file) {
file.status = 'uploading'
return false
},
// 移除一个上传的文件
handleRemove (file) {
const index = this.fileList.indexOf(file)
this.fileList.splice(index, 1)
},
// 上传完成之后的文件处理
handleChange (info) {
console.log('info', info)
const { file, fileList } = info
if (file.status === 'removed') {
this.handleRemove(file)
} else {
this.fileList = fileList
let index
for (let i = 0; i < fileList.length; i++) {
if (fileList[i].uid === file.uid) {
index = i
break
}
}
this.handleUpload(file, index)
}
},
// 上传完成之后处理文件
handleUpload (file, index) {
this.handleReadExcel(file)
this.fileList[index].status = 'done'
},
// (重点)把文件按照二进制读取
handleReadExcel (file) {
const that = this
const fileReader = new FileReader()
fileReader.onload = ev => {
try {
const fileData = ev.target.result
const workbook = XLSX.read(fileData, {
type: 'binary'
})
const wsname = workbook.SheetNames[0] // 取第一张表
const snArr = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]) // 生成json表格内容
// console.log(snArr) // 读取到的SN列表
// 遍历SN放入Set集合 snSet
that.dataGrid.snSet.clear() // 清空一下之前的Set
snArr.forEach(item => {
that.dataGrid.snSet.add(item.sn)
})
console.log(that.dataGrid.snSet)
// 处理完SN列表之后可以开放OK按钮
this.enableSubmit = false
} catch (e) {
return false
}
}
fileReader.readAsBinaryString(file)
},
最后提示一点不要忘了引入解析xlsl的包,需要下载再引入
import XLSX from 'xlsx'