1.先安装xlsx,在终端运行以下命令
npm install xlsx
2.编写上传组件,这里是element-UI
<el-upload
v-loading="loading"
element-loading-text="上传中请稍后"
element-loading-background="rgba(0, 0, 0, 0.8)"
drag
accept=".xls, .xlsx,.csv"
action="#"
:auto-upload="false"
:on-change="uploadFile"
:multiple="false"
:show-file-list="false"
:disabled="loading"
>
<el-icon class="el-icon--upload"><upload-filled /></el-icon>
<div class="el-upload__text">拖拽上传 或 <em>点击上传</em></div>
</el-upload>
3.定义标题名称,因为我希望输出得到的内容是
[
{
"weight":'xxx',
"length":'xx',
...
}
]
data() {
return {
labelMap: {
重量: 'weight',
长: 'length',
宽: 'width',
高: 'height',
国家: 'country',
收件人姓名: 'name',
电话: 'phone',
邮编: 'zip'
...
} as Record<string, any>,//这个是注明类型,不用后面匹配表头时会报错
}
4.上传并解析,匹配表头重组数组
readFile(file: any) {
return new Promise((resovle: any) => {
const reader = new FileReader()
reader.readAsArrayBuffer(file)
reader.onload = (ev) => {
resovle(ev.target?.result)
}
})
},
async uploadFile(file: any, fileList: any) {
this.loading = true
const fileRow = file.raw
if (!fileRow) {
ElMessage.error('文件上传失败')
return
} else {
const data = await this.readFile(fileRow)
const workBook = xlsx.read(data, { type: 'binary' })
const workSheet = workBook.Sheets[workBook.SheetNames[0]]
const result = xlsx.utils.sheet_to_json(workSheet)
const tempList = [] as any
//匹配表头重组数组
result.map(async (item: any) => {
const excelItem: Record<string, any> = {}
for (const key in this.labelMap) {
excelItem[this.labelMap[key] as string] = item[key]
}
tempList.push(excelItem)
})
//赋值给渲染前端的数组
this.packageList = tempList
this.loading = false
}
},
输出内容大致是这样的