一、安装xlsx
可以先了解js-xlsx插件(SheetJS),github地址:https://github.com/SheetJS/sheetjs
npm install xlsx
二、引入xlsx
import XLSX from 'xlsx'
三、模板
<el-upload
class="import hidden-xs-only"
ref="upload"
action="/"
:show-file-list="false"
:on-change="importExcel"
:auto-upload="false"
>
<el-button slot="trigger" size="small" type="primary">
导入Excel表格
</el-button>
</el-upload>
四、导入方法
//导入
importExcel(file) {
// let file = file.files[0] // 使用传统的input方法需要加上这一步
const types = file.name.split('.')[1]
const fileType = ['xlsx','xls'].some((item) => item === types)
if (!fileType) {
this.$message('格式错误!请下载词库导入模板编辑后上传')
return false
}
this.file2Xce(file).then((tabJson) => {
if (tabJson && tabJson.length > 0) {
this.xlsxJson = tabJson//Excel表格的数据
//...
//...
//处理表格数据的操作
}
})
},
file2Xce(file) {
return new Promise(function(resolve) {
const reader = new FileReader()
reader.onload = function(e) {
const data = e.target.result
this.wb = XLSX.read(data, {
type: 'binary',
})
const result = []
this.wb.SheetNames.forEach((sheetName) => {
result.push({
sheetName: sheetName,
sheet: XLSX.utils.sheet_to_json(this.wb.Sheets[sheetName]),
})
})
resolve(result)
}
reader.readAsBinaryString(file.raw)
// reader.readAsBinaryString(file) // 传统input方法
})
},
//导入 end
非常感谢