参考element ui的写法
父组件代码
<template>
<div class="app-container">
<upload-excel-component :on-success="handleSuccess" :before-upload="beforeUpload" />
<el-table :data="tableData" border highlight-current-row style="width: 100%;margin-top:20px;">
<el-table-column v-for="item of tableHeader" :key="item" :prop="item" :label="item" />
</el-table>
</div>
</template>
<script>
// 导入注册为组件
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import { getImportJsData } from '@/utils/excel'
import { batchEmployeeAPI } from '@/api/employee'
export default {
name: 'UploadExcel',
components: { UploadExcelComponent },
data() {
return {
tableData: [],
tableHeader: []
}
},
methods: {
// 导入之前做的事情
beforeUpload(file) {
// file 是传入的excel的文件
const isLt1M = file.size / 1024 / 1024 < 1
// 判端传入的是否小于1M 如果小于就return true
// 必须写return true 这样才会执行后续的代码
if (isLt1M) {
return true
}
this.$message({
message: 'Please do not upload files larger than 1m in size.',
type: 'warning'
})
return false
},
// 传入excel之后做的事
async handleSuccess({ results, header }) {
console.log(results, header)
// results 是传入的每一项数据转换为js形式
// header 是传入之后表头的名字
const headerRelation = {
'姓名': 'username',
'手机号': 'mobile',
'入职日期': 'timeOfEntry',
'工号': 'workNumber',
'聘用形式': 'formOfEmployment',
'部门': 'departmentName'
}
const data = getImportJsData(results, headerRelation) //这个方法是转换为需要的数据
await batchEmployeeAPI(data)
this.$message.success('添加成功')
// 跳转回上一个页面
this.$router.go(-1)
this.tableData = results
this.tableHeader = header
}
}
}
</script>
父组件中处理数据的方法
/**
* @description: 获取导出时的表头数据和表格数据
* @param {*} { sourceData:后端返回的源数据,header:表格头中因为对应关系}
* @return {*}
*/
// 处理函数中对key判断如果发生当前它是聘用形式 通过枚举做一下处理 返回中文
// 枚举处理函数 根据1/2返回正式或者非正式
function transEmployment(value) {
const TYPES = {
1: '正式',
2: '非正式'
}
return TYPES[value]
}
export function getExportData(sourceData, headerRelation) {
const data = sourceData.map(item => {
const arr = []
Object.values(headerRelation).forEach(key => {
// 关键位置:把所有的value不做任何处理直接扔到了数组中 导致excel是源数据
// 如果是当前要处理的是聘用形式 就先转化一步再添加到数组中
if (key === 'formOfEmployment') {
const formatValue = transEmployment(item[key])
arr.push(formatValue)
} else {
arr.push(item[key])
}
})
return arr
})
return {
data
}
}
/**
* @description: 获取导入时的处理之后的接口数据
* @param {*} results
* @return {*}
*/
export function getImportJsData(results, headerRelation) {
const newArr = []
// 将所有的中文key转换成英文key 然后添加到新数组中
results.forEach(item => {
const map = {}
Object.keys(item).forEach(key => {
map[headerRelation[key]] = item[key]
})
newArr.push(map)
})
// 时间处理
newArr.forEach(item => {
Object.keys(item).forEach(key => {
if (key === 'timeOfEntry') {
item[key] = new Date(formatDate(item[key], '/'))
}
})
})
return newArr
}
export function formatDate(numb, format) {
const time = new Date((numb - 1) * 24 * 3600000 + 1)
time.setYear(time.getFullYear() - 70)
const year = time.getFullYear() + ''
const month = time.getMonth() + 1 + ''
const date = time.getDate() - 1 + ''
if (format && format.length === 1) {
return year + format + (month < 10 ? '0' + month : month) + format + (date < 10 ? '0' + date : date)
}
return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
}
子组件代码
<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>
// 因为这个xlsx版本比较低,所以要使用* as
import * as XLSX from 'xlsx'
export default {
props: {
// 接受父组件传过来的俩个数据,数据类型是function格式
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>
前端主导excel导入流程
后端主导的流程