安装依赖
> npm install -S file-saver xlsx
> npm install -D script-loader
代码片段-html
// handleUpBtns 触发导入事件的方法(table是用来判定导入数据的用处)
<div style="margin-bottom: 10px">
<span
style="margin-right: 10px"
><a-button
@click="handleUpBtns('table')"
>导入 <input type="file" ref="refFile" style="display: none" @change="handleFiles" /></a-button></span
><a-button>导出</a-button>
</div>
代码片段 - js
值得注意的是再引用xlsx的时候vue3和vue2写法不同
vue2:import xlsx from ‘xlsx’
vue3:import * as XLSX from ‘xlsx’
// 上传文件
handleUpBtns (item) {
this.$refs.refFile.click() // 触发文件按钮点击事件 vue2 写法
refFile.value.click() // 触发文件按钮点击事件 vue3 写法
this.status = item
},
handleFiles () {
const selectedFile = this.$refs.refFile.files[0]
// selectedFile中可以获取到文件名和文件大小 selectedFile.name, selectedFile.size
this.file = selectedFile
this.fileName = selectedFile.name
/*
在得到selectedFile文件之后,可以直接将selectedFile文件通过接口传递到后端,进行文件内容的处理
如果文件需要在前端进行处理,就需要借助FileReader读取文件内容
在前端可以进行一些简单的文件处理
比如判断文件的大小是否超出规定内容
判断文件的格式是否符合要求等
*/
// 下面的操作对当前的文件进行读取、获取文件内容,可以借助XLSX将excel文件内容转成json格式的数据
const reader = new FileReader()
reader.readAsBinaryString(selectedFile)
/*
FileReader共有4种读取方法:
1.readAsArrayBuffer(file):将文件读取为ArrayBuffer。
2.readAsBinaryString(file):将文件读取为二进制字符串
3.readAsDataURL(file):将文件读取为Data URL
4.readAsText(file, [encoding]):将文件读取为文本,encoding缺省值为'UTF-8'
*/
reader.onload = (evt) => {
try {
const data = evt.target.result
const workbook = XLSX.read(data, { type: 'binary' })
// 以二进制流方式读取得到整份excel表格对象 type: 'base64'
const wsname = workbook.SheetNames[0] // 取第一张表 如果有多张数据表 可以使用循环遍历
const sheet = workbook.Sheets[wsname]
const jsonData = XLSX.utils.sheet_to_json(sheet) // 生成json数据
// jsonData 就是导入的excel数据了
// 这里可以 我没有接api 就在本地使用了
if (this.status == 'tree') {
jsonData.map((el) => {
el.scopedSlots = { title: 'custom' }
el.key = el.id
if (el.name == null) {
el.name = 'null'
} else if (el.commonName == null) {
el.commonName = 'null'
}
})
console.log(jsonData)
// 缓存在本地 持久化存储
localStorage.treeData = JSON.stringify(jsonData)
this.treeData = this.toTree(jsonData)
} else {
console.log(this.status)
this.data = jsonData
localStorage.table = JSON.stringify(this.data)
this.cacheData = this.data.map((item) => ({ ...item }))
}
this.$message.success('导入成功!')
this.status = ''
} catch (err) {
console.error('出错了!', err)
}
}
},