First go to the official warehouse to pull the code
There are two code files related to import:
- Define components:
src/components/UploadExcel/index.vue
- Use components:
src/views/excel/upload-excel.vue
1. Duplicate components
Generally copied to src/components/UploadExcel/index.vue
2. Download dependencies
package.json directly add this line, and then npm i downloads the required dependencies
3. Build and import excel page
<template>
<div class="import-container">
<div class="app-container">
<el-card>
<!-- 具体页面结构 -->
导入excel
<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>
</el-card>
</div>
</div>
</template>
<script>
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
export default {
components: { UploadExcelComponent },
data() {
return {
tableData: [],
tableHeader: []
}
},
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
},
handleSuccess({ results, header }) {
console.log('内容', results)
console.log('表头', header)
this.tableData = results
this.tableHeader = header
}
}
}
</script>
<style lang="scss" scoped></style>
4. router routing configuration
{
path: '/importExcel',
component: Layout,
children: [{ path: '', component: () => import('@/views/employees/importExcel.vue') }],
hidden: true
},
5. Jump page
Where excel components are needed
For example, button registration click eventthis.$router.push('/importExcel')
6. Function explanation
handleSuccess is the callback function executed after the imported excel file is successfully read, results is the content, and header is the header
How to convert the data format, please see the next article