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)
}
},
}