安装
npm install xlsx --save
引用
import * as XLSX from 'xlsx/xlsx.mjs'
结合element
<el-upload
action
accept = ".xlsx, .xls"
:auto-upload="false"
:show-file-list="false"
:http-request="uploadFile">
<el-button type="primary">导入excel</el-button>
</el-upload>
async uploadFile(params) {
const _file = params.file
const fileReader = new FileReader()
fileReader.onload = ev => {
try {
const data = ev.target.result
console.log(data)
const workbook = XLSX.read(data, {
type: 'binary',
})
for (let sheet in workbook.Sheets) {
//循环读取每个文件
const sheetArray = XLSX.utils.sheet_to_json(workbook.Sheets[sheet])
//若当前sheet没有数据,则continue
if (sheetArray.length == 0) {
continue
}
console.log('读取文件')
//解析返回的json
console.log(sheetArray)
}
} catch (e) {
this.$message.warning('文件类型不正确!')
}
}
fileReader.readAsBinaryString(_file)
},