vue + elementUI导入Excel读取文件内容
实现导入Excel数据内容,渲染到页面
代码
导入按钮 代码片
.
// 导入按钮
<el-upload class="upload-demo" action="" :on-change="handleChange" :show-file-list="false" :auto-upload="false">
<el-button type="primary" size="small" onclick="">批量导入</el-button>
</el-upload>
声明变量 代码片
.
data() {
return {
//excel读取
tableData: [],
fileContent: '',
file: '',
data: ''
};
},
js代码片
.
// 读入Excel文件内容: 核心部分代码(handleChange 和 importfile)
handleChange (file) {
this.fileContent = file.raw
const fileName = file.name
const fileType = fileName.substring(fileName.lastIndexOf('.') + 1)
if (this.fileContent) {
if (fileType === 'xlsx' || fileType === 'xls') {
this.importfile(this.fileContent)
} else {
this.$message({
type: 'warning',
message: '附件格式错误,请重新上传!'
})
}
} else {
this.$message({
type: 'warning',
message: '请上传附件!'
})
}
},
importfile (obj) {
const reader = new FileReader()
const _this = this
reader.readAsArrayBuffer(obj)
reader.onload = function () {
const buffer = reader.result
const bytes = new Uint8Array(buffer)
const length = bytes.byteLength
let binary = ''
for (let i = 0; i < length; i++) {
binary += String.fromCharCode(bytes[i])
}
const XLSX = require('xlsx')
const wb = XLSX.read(binary, {
type: 'binary'
})
const outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])
this.data = [...outdata]
const arr = []
this.data.map(v => {
const obj = {}
//换成你的字段名称
//obj.name: 字段名 , v.姓名:Excel中表单标题行名
obj.name = v.姓名
obj.no = v.员工号
arr.push(obj)
})
//_this.tableData换成你要导入的table表
_this.tableData = _this.tableData.concat(arr)
}
},