操作步骤:
-
后端提供一个excel模板文件。
-
用户填写这个excel模板文件。
-
上传这个文件,实现批量导入功能。
思路:
前端主导(工作大量在前端)
上传excel文件,把excel文件的内容读出来,还原成最基本的行列结构,按后端的接口要求回传过去。
- 前端读excel文件,调接口
实操:
-
定义组件:
src/components/UploadExcel/index.vue(组件需要加载xlsx包)
-
使用组件:
src/views/import/upload-excel.vue
-
安装插件: npm install xlsx -S
-
注册组件(全局或局部)
这个组件引入了XLSX包, 需要给它提供两个props:
-
beforeUpload:上传之前的函数
-
onSuccess: 成功调用之后的函数
<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 {
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>
使用组件:src/views/import/upload-excel.vue
<template>
<div>
// 加载 UploadExcel 组件 onSuccess: 成功调用之后的函数
<UploadExcel :on-success="handleSuccess"></UploadExcel>
</div>
</template>
<script>
import { formatExcelDate } from '@/utils/index'
import { importEmployee } from '@/api/employees'
import UploadExcel from '@/components/UploadExcel/index.vue'
export default {
name: 'Import',
components: { UploadExcel },
methods: {
// 数组转换 (转换后台需要的格式)
formData(header, results) {
// 转换需要的数据
const mapInfo = {
入职日期: 'timeOfEntry',
手机号: 'mobile',
姓名: 'username',
转正日期: 'correctionTime',
工号: 'workNumber',
部门: 'departmentName',
聘用形式: 'formOfEmployment'
}
// console.log(results)
// results: [{姓名:xxx, 手机号:xxxx},{姓名:xxx, 手机号:xxxx}]
// data: [{username:xxx, mobile:xxxx},{username:xxx, mobile:xxxx}]
const data = results.map(obj => {
// obj是{姓名:xxx, 手机号:xxxx}
const newObj = {} // 新数组里的新对象,相当于是深拷贝
Object.keys(obj).forEach(zhKey => {
const enKey = mapInfo[zhKey] // 从中文key转为英文key
if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
// 对日期做特殊处理(有一个专门的函数来处理excel读出来的日期时间)
// new Date('2020-12-12') 做这个转换,是因为后端需要标准日期格式
newObj[enKey] = new Date(formatExcelDate(obj[zhKey]))
} else {
newObj[enKey] = obj[zhKey] // 将每一项的中文属性给newObj
}
})
return newObj
})
return data
},
// 当读入数据成功,输出里面的内容;
async handleSuccess({ header, results }) {
// 1.根据后台要求,进行格式转换
// 将格式转换封装在一个函数中
const data = this.formData(header, results)
console.log('数据', data)
// 2.发送请求
const res = await importEmployee(data)
console.log('导入的文件', res)
this.$router.back()
// console.log(header, results)
}
}
}
</script>
<style></style>
时间日期转换:
加载:import { formatExcelDate } from '@/utils/index'
在 utils/index.js 中定义
// 把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)
}