1.安装插件(版本0.18.5)
npm i xlsx
2.封装插件
<template>
<div class="container">
<slot></slot>
</div>
</template>
<script>
import * as XLSX from 'xlsx'
export default {
name: 'ReadExcel',
props: {
filePath: {
type: String,
default: ''
}
},
mounted() {
this.readExcel()
},
methods: {
readExcel() {
// 假设你的xlsx文件位于public目录下,并命名为'example.xlsx'
// console.log('filePath', this.filePath)
// 使用fetch获取public下的文件
fetch(this.filePath)
.then(res => res.arrayBuffer())
.then(data => {
// 读取xlsx文件
const workbook = XLSX.read(data, { type: 'buffer' })
// 获取第一个工作表
const firstSheetName = workbook.SheetNames[0]
const worksheet = workbook.Sheets[firstSheetName]
// 将工作表转换为JSON
const tableData = XLSX.utils.sheet_to_json(worksheet)
this.$emit('getData', tableData)
})
}
}
}
</script>
3.页面使用(filePath文件路径为public下的user.xlsx)
<template>
<div class="app-container">
<ReadExcel filePath="/user.xlsx" @getData="getData">
<el-table :data="tableData" border style="width: 100%">
<el-table-column align="center" prop="用户编号" label="用户编号" />
<el-table-column align="center" prop="用户名称" label="用户名称" />
<el-table-column align="center" prop="用户昵称" label="用户昵称" />
<el-table-column align="center" prop="部门" label="部门" />
<el-table-column align="center" prop="手机号码" label="手机号码" />
</el-table>
<div class="pagination" style="display: flex; justify-content: flex-end; margin-top: 20px">
<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[5, 10, 15, 20]" :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="tableData.length" />
</div>
</ReadExcel>
</div>
</template>
<script>
import ReadExcel from '@/components/ReadExcel'
export default {
name: 'User',
components: {
ReadExcel
},
data() {
return {
listQuery: {
pageNum: 1,
pageSize: 5
},
data: []
}
},
computed: {
tableData() {
return this.data.slice((this.listQuery.pageNum - 1) * this.listQuery.pageSize, this.listQuery.pageNum * this.listQuery.pageSize)
}
},
methods: {
getData(val) {
this.data = val
},
handleSizeChange(val) {
this.listQuery.pageSize = val
},
handleCurrentChange(val) {
this.listQuery.pageNum = val
}
}
}
</script>