<template>
<div>
<p class="top">支持通过excel文件批量员工信息,请按`在这里插入代码片`照模板格式编辑员工信息后上传、下载模板。</p>
<input class="input-file" type="file" @change="exportData"
accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"/>
<el-button type="primary" @click="btnClick">导入EXCEL</el-button>
<p v-if="isVisibleSuccess" class="import-success">导入成功</p>
<div class="footer">
<el-button @click="cancel">取消</el-button>
<el-button type="primary" @click="onSubmit">立即创建</el-button>
</div>
</div>
</template>
<script>
import XLSX from 'xlsx'
export default {
name: 'importFile',
data() {
return {
outdata: null,
isVisibleSuccess: false,
index: 1, //上传顺序
}
},
methods: {
btnClick() {
this.isVisibleSuccess = false
document.querySelector('.input-file').value = ''
document.querySelector('.input-file').click()
},
exportData(event) {
console.log(document.querySelector('.input-file'));
if (!event.currentTarget.files.length) {
return
}
let _this = this
// 拿取文件对象
var f = event.currentTarget.files[0]
// 用FileReader来读取
var reader = new FileReader()
// 重写FileReader上的readAsBinaryString方法
FileReader.prototype.readAsBinaryString = function(f) {
var binary = ''
var wb // 读取完成的数据
var outdata // 你需要的数据
var reader = new FileReader()
reader.onload = function(e) {
// 读取成Uint8Array,再转换为Unicode编码(Unicode占两个字节)
var bytes = new Uint8Array(reader.result)
var length = bytes.byteLength
for (var i = 0; i < length; i++) {
binary += String.fromCharCode(bytes[i])
}
// 接下来就是xlsx了,具体可看api
wb = XLSX.read(binary, {
type: 'binary'
})
// console.log(wb);
outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[1]])
_this.isVisibleSuccess = true //显示成功
_this.outdata = outdata //获取数据
console.log(outdata)
}
reader.readAsArrayBuffer(f)
}
reader.readAsBinaryString(f)
},
// 提交
onSubmit() {
console.log(this.outdata);
let data = [];
this.outdata.forEach((item, index) => {
data.push({
iname: item['姓名'] || '',
ID_number: item['身份证号码'] || '',
sex: item['性别'] || '',
mobile: item['手机号码'] || '',
dept1: item['一级部门'] || '',
dept2: item['二级部门'] || '',
dept3: item['三级部门'] || '',
work_name: item['岗位'] || '',
})
})
},
}
}
</script>
<style lang="scss" scoped>
.input-file {
display: none;
}
.top {
margin-bottom: 15px;
}
.footer {
text-align: right;
margin-top: 15px;
}
.import-success {
margin-top: 10px;
color: rgba(10, 180, 105, 1);
}
</style>