需求: 通过表格一键导入数据
表格模板:
导入按钮:
<el-upload
ref="upload"
class="filter-item"
style="margin-left: 10px"
action="/"
accept=".csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
:multiple="false"
:show-file-list="false"
:auto-upload="false"
:on-change="importExl"
>
<el-button
slot="trigger"
icon="el-icon-copy-document"
>导入表格数据</el-button>
</el-upload>
主要功能代码:
import XLSX from 'xlsx'
// 表格内容获取
file2Xce(file) {
return new Promise(function(resolve, reject) {
const reader = new FileReader()
reader.onload = function(e) {
const data = e.target.result
const wb = XLSX.read(data, {
type: 'binary'
})
const result = []
wb.SheetNames.forEach((sheetName) => {
result.push({
sheetName: sheetName,
sheet: XLSX.utils.sheet_to_json(wb.Sheets[sheetName])
})
})
resolve(result)
}
reader.readAsBinaryString(file.raw)
})
},
// 表格内容转换
setfileData(obj) {
const importParams = {
'姓名*': 'fullName',
'性别*': 'sex',
'手机号*': 'mobile',
'身份证号码': 'certNo'
}
const params = {
fullName: '',
sex: '',
mobile: '',
certNo: ''
}
for (const i in obj) {
const key = importParams[i]
if (key === 'sex') {
params[key] = obj[i] === '男' ? 1 : 2
} else {
params[key] = obj[i]
}
}
return params
}
// 导入表格
importExl(file) {
this.file2Xce(file).then(tabJson => {
if (tabJson && tabJson.length > 0) {
const xlsxJson = tabJson
const params = []
xlsxJson.forEach(ele => {
ele.sheet.forEach(obj => {
params.push(this.setfileData(obj))
})
})
// params 转换后的表格内容
// 上传api...
}
})
},