<template>
<el-upload
ref="upload"
class="upload-demo"
:limit="1"
:on-exceed="handleExceed"
:show-file-list="false"
action
accept=".xlsx,.xls"
:auto-upload="false"
:on-change="handleChange"
>
<template #trigger>
<el-button type="primary" :icon="Download" plain>导入</el-button>
</template>
</el-upload>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { genFileId } from 'element-plus'
import { Download } from '@element-plus/icons-vue'
//excel文件数据解析
import * as XLSX from 'xlsx'
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
const upload = ref<UploadInstance>()
const handleExceed: UploadProps['onExceed'] = (files) => {
upload.value!.clearFiles()
const file = files[0] as UploadRawFile
file.uid = genFileId()
upload.value!.handleStart(file)
}
interface tableConfigType {
name: {
text: string
type: string
}
businessName: {
text: string
type: string
}
}
const tableConfig = {
name: {
text: '姓名',
type: 'string'
},
businessName: {
text: '工号',
type: 'string'
},
}
// 按照二进制读取文件 excel文件的处理
const readFile = (file: any) => {
return new Promise((resolve) => {
const reader = new FileReader()
reader.readAsBinaryString(file)
reader.onload = (e: any) => {
resolve(e.target.result)
}
})
}
const handleChange: UploadProps['onChange'] = async (uploadFile) => {
//这个是上传的文件
let file = uploadFile.raw
console.log(uploadFile, 'file')
//没有文件
if (!file) return
//读取file中的数据
//把文件解析成二进制数据,把二级制数据变成excel表格式的数据
let data: any = await readFile(file)
let workbook = XLSX.read(data, { type: 'binary' })
//拿到第一个sheet表的数据,把第一个表格的数据转换成JSON数据
const worksheet = workbook.Sheets[workbook.SheetNames[0]]
data = XLSX.utils.sheet_to_json(worksheet)
const arr: any[] = []
data.forEach((item: any) => {
let obj: any = {}
for (let key in tableConfig) {
// 此处keyof是为了解决直接使用key索引会报错问题
let v = tableConfig[key as keyof tableConfigType]
v = item[v.text] || ''
obj[key] = v
}
arr.push(obj)
})
console.log(arr, '表格数据')
}
</script>
<style lang="scss" scoped>
.el-button {
font-size: 12px;
font-weight: 400;
height: 28px;
padding: 8px 16px;
margin-left: 12px;
--el-color-primary: #37f;
}
.el-button--primary.is-plain {
--el-color-primary-light-9: #fff;
--el-color-primary-light-5: var(--defalut--blue);
}
</style>
前端导入Excel表格获取数据(Vue3+TS+Element)
最新推荐文章于 2024-04-29 18:09:32 发布