<el-upload
class="upload-demo" ref="upload" accept=".xls,.xlsx"
action="https://localhost:8081/posts/"
:on-change="upload"
:show-file-list="false"
:auto-upload="false"
>
<el-button slot="trigger" size="large">导入excel</el-button>
</el-upload>
import xlsx from "xlsx"
upload (file, fileList) {
const files = { 0: file.raw }
this.readExcel(files)
},
readExcel (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 = (files) => {
try {
const data = files.target.result
const workbook = xlsx.read(data, {
type: 'binary'
})
const wsname = workbook.SheetNames[0]
const ws = xlsx.utils.sheet_to_json(workbook.Sheets[wsname])
console.log(ws, 'ws是表格里的数据,且是json格式')
this.menuData = ws
this.$refs.upload.value = ''
} catch (e) {
console.log(e)
return false
}
}
fileReader.readAsBinaryString(files[0])
}