后端提供一个excel模板文件
用户填写这个excel模板文件
上传这个文件,实现批量导入功能
1.定义组件UploadExcel(src/components/UploadExcel/index.vue)
<template>
<div>
<input ref="excel-upload-input" class="excel-upload-input" type="file" accept=".xlsx, .xls" @change="handleClick">
<div class="drop" @drop="handleDrop" @dragover="handleDragover" @dragenter="handleDragover">
Drop excel file here or
<el-button :loading="loading" style="margin-left:16px;" size="mini" type="primary" @click="handleUpload">
Browse
</el-button>
</div>
</div>
</template>
<script>
import XLSX from 'xlsx'
export default {
name: 'UploadExcel',
props: {
beforeUpload: Function, // eslint-disable-line
onSuccess: Function// eslint-disable-line
},
data() {
return {
loading: false,
excelData: {
header: null,
results: null
}
}
},
methods: {
generateData({ header, results }) {
this.excelData.header = header
this.excelData.results = results
this.onSuccess && this.onSuccess(this.excelData)
},
handleDrop(e) {
e.stopPropagation()
e.preventDefault()
if (this.loading) return
const files = e.dataTransfer.files
if (files.length !== 1) {
this.$message.error('Only support uploading one file!')
return
}
const rawFile = files[0] // only use files[0]
if (!this.isExcel(rawFile)) {
this.$message.error('Only supports upload .xlsx, .xls, .csv suffix files')
return false
}
this.upload(rawFile)
e.stopPropagation()
e.preventDefault()
},
handleDragover(e) {
e.stopPropagation()
e.preventDefault()
e.dataTransfer.dropEffect = 'copy'
},
handleUpload() {
this.$refs['excel-upload-input'].click()
},
handleClick(e) {
const files = e.target.files
const rawFile = files[0] // only use files[0]
if (!rawFile) return
this.upload(rawFile)
},
upload(rawFile) {
this.$refs['excel-upload-input'].value = null // fix can't select the same excel
if (!this.beforeUpload) {
this.readerData(rawFile)
return
}
const before = this.beforeUpload(rawFile)
if (before) {
this.readerData(rawFile)
}
},
readerData(rawFile) {
this.loading = true
return new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onload = e => {
const data = e.target.result
const workbook = XLSX.read(data, { type: 'array' })
const firstSheetName = workbook.SheetNames[0]
const worksheet = workbook.Sheets[firstSheetName]
const header = this.getHeaderRow(worksheet)
const results = XLSX.utils.sheet_to_json(worksheet)
this.generateData({ header, results })
this.loading = false
resolve()
}
reader.readAsArrayBuffer(rawFile)
})
},
getHeaderRow(sheet) {
const headers = []
const range = XLSX.utils.decode_range(sheet['!ref'])
let C
const R = range.s.r
/* start in the first row */
for (C = range.s.c; C <= range.e.c; ++C) { /* walk every column in the range */
const cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })]
/* find the cell in the first row */
let hdr = 'UNKNOWN ' + C // <-- replace with your desired default
if (cell && cell.t) hdr = XLSX.utils.format_cell(cell)
headers.push(hdr)
}
return headers
},
isExcel(file) {
return /\.(xlsx|xls|csv)$/.test(file.name)
}
}
}
</script>
<style scoped>
.excel-upload-input{
display: none;
z-index: -9999;
}
.drop{
border: 2px dashed #bbb;
width: 600px;
height: 160px;
line-height: 160px;
margin: 0 auto;
font-size: 24px;
border-radius: 5px;
text-align: center;
color: #bbb;
position: relative;
}
</style>
2.自定义时间格式转换工具函数(src/utils/index.js)
由于excel文件时间有自己的格式所以需要转换成标准时间格式
// 把excel文件中的日期格式的内容转回成标准时间
// https://blog.csdn.net/qq_15054679/article/details/107712966
export function formatExcelDate(numb, format = '/') {
const time = new Date((numb - 25567) * 24 * 3600000 - 5 * 60 * 1000 - 43 * 1000 - 24 * 3600000 - 8 * 3600000)
time.setYear(time.getFullYear())
const year = time.getFullYear() + ''
const month = time.getMonth() + 1 + ''
const date = time.getDate() + ''
if (format && format.length === 1) {
return year + format + month + format + date
}
return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
}
3.给导入按钮添加点击事件实现页面跳转
<el-button
v-allow="'导入'"
type="warning"
size="small"
@click="$router.push('/import')"
>导入excel</el-button>
4.在导入页面导入组件和工具函数
<template>
<div class="department-container">
<div class="app-container">
<el-card>
<!-- 具体页面结构 -->
excel导入员工信息
<UploadExcel
:on-success="handleSuccess"
:before-upload="beforeUpload"
/>
</el-card>
</div>
</div>
</template>
<script>
// import UploadExcel from '@/components/UploadExcel/index.vue'
import { formatExcelDate } from '@/utils/index'
import { importEmployee } from '@/api/employees'
export default {
name: 'Import',
// components: { UploadExcel },
methods: {
beforeUpload(file) {
const isLt1M = file.size / 1024 / 1024 < 1
if (isLt1M) {
return true
}
this.$message({
message: 'Please do not upload files larger than 1m in size.',
type: 'warning'
})
return false
},
// 文件导入
transExcel(results) {
const mapInfo = {
'入职日期': 'timeOfEntry',
'手机号': 'mobile',
'姓名': 'username',
'转正日期': 'correctionTime',
'工号': 'workNumber',
'部门': 'departmentName',
'聘用形式': 'formOfEmployment'
}
return results.map(zhObj => {
const enObj = {}
const zhKeys = Object.keys(zhObj) // ['姓名', '手机号']
zhKeys.forEach(zhKey => {
const enKey = mapInfo[zhKey]
if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
// 后端需要的日期格式是标准时间
enObj[enKey] = new Date(formatExcelDate(zhObj[zhKey]))
} else {
enObj[enKey] = zhObj[zhKey]
}
})
return enObj
})
},
async doImport(data) {
try {
const res = await importEmployee(data)
console.log('importEmployee', res)
this.$message.success('导入成功')
// 页面后退
this.$router.back()
} catch (err) {
console.log('importEmployee', err)
this.$message.error('导入失败')
}
},
// 1. 把数据从excel文件读入到浏览器内存
handleSuccess({ header, results }) {
console.log(111)
console.log(header, results)
// 2. 按接口要求 组装数据
const data = this.transExcel(results)
console.log('按接口要求 组装数据', data)
// 3. 调用接口做上传
this.doImport(data)
}
}
}
</script>
实现excel导入功能