The import
1 Install required plug-ins
npm install xlsx -S
Copy the code
Import UploadExcel component and register as global
Will provide the components of the vue – element – admin copied to your own project under SRC/components/UploadExcel panjiachen. Making. IO/vue – element… Github.com/PanJiaChen/… Register as a global component in components/index.js
.import UploadExcel from './UploadExcel'
export default {
// Plugin initialization, plugin to provide you with global functions, can be configured here
install(Vue) {
// Register the component globally. Vue.component('UploadExcel', UploadExcel) // Register to import excel components}}Copy the code
3 Configure routes and create an Import component
The import components
<template>
<upload-excel :on-success="handleSuccess" />
</template>
<script>
export default {
name: 'Import'.methods: {
handleSuccess({ header, results }) {
console.log(header, results)
}
}
}
</script>
Copy the code
Configure the routing
{
path: '/import'.component: '... '.hidden: true.// Do not display to the left menu
children: [{
path: ' '.component: () = > import('@... ')}}]Copy the code
4 Test the component effect
5 Importing Excel (example: Employee information)
5.1 Encapsulation Interfaces
export function importEmployee(data) {
returnrequest({ ... })}Copy the code
5.2 Data Conversion
// For each object in the original array
// (1) find all the Chinese keys
// (2) get the corresponding English key
// (3) join a new object
transExecl(data) {
const mapInfo = {
'Entry Date': 'timeOfEntry'.'Mobile phone Number': 'mobile'.'name': 'username'.'Date of conversion': 'correctionTime'.'working': 'workNumber'.'department': 'departmentName'.'Form of Employment': 'formOfEmployment'
}
return data.map(oldObj= > {
const newObj = {}
const oldKeys = Object.keys(oldObj)
oldKeys.forEach(oldKey= > {
const newKey = mapInfo[oldKey]
if (newKey === 'timeOfEntry' || newKey === 'correctionTime') {
newObj[newKey] = new Date(formatExcelDate(oldObj[oldKey]))
}
newObj[newKey] = oldObj[oldKey]
})
return newObj
})
}
Copy the code
5.3 Time Conversion
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)
}
Copy the code
5.4 Used on the Page
methods:{
...
// Read data from excel files into browser memory
handleSuccess({ header, results }) {
// console.log(header, results)
// console.log(this.transExecl(results))
this.doImport(this.transExecl(results))
},
async doImport(data) {
try {
await importExcel(data)
this.$router.back()
} catch (error) {
console.log(error)
}
}
}
Copy the code