前端上传Excel,解析并渲染到页面上--ts脚本

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
			}
		},



输出内容大致是这样的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值