vue3+Ts实现渲染excel表格数据

先看效果:

UI界面展示

Excel展示:

 

 代码如下:

这里使用的是vue3组件库 Naive ui

<template>
	<div>
		<div class="container">
			<span style="font-size: 18px"><b>评价关系</b></span>
			<span style="font-size: 18px"><b>评估表</b></span>
			<n-button @click="handleUploadClick">上传 Excel 文件</n-button>
			<input type="file" ref="fileInput" @change="handleFileChange" hidden />
		</div>
		<n-data-table :columns="columns" :data="tableData" />
	</div>
</template>

<script setup lang="ts">
	import * as XLSX from 'xlsx'
	import { ref, reactive, toRefs, watch, onMounted, getCurrentInstance } from 'vue'
	import { NButton, NDataTable, NUpload } from 'naive-ui'

	const fileInput = ref(null as HTMLInputElement | null)
	const columns = [
		// key 是表头的字段名
		// title 是表头的文字
		{ title: '工号', key: '工号' },
		{ title: '被评人', key: '被评人' },
		{ title: '上级', key: '上级' },
		{ title: '同级', key: '同级' },
		{ title: '下级', key: '下级' },
		{ title: '客户', key: '客户' },
	]
	const tableData: any = ref([])

	function handleUploadClick() {
		if (fileInput.value) {
			fileInput.value.click()
		}
	}
	function handleFileChange(event: Event) {
		const files = (event.target as HTMLInputElement).files
		if (files && files.length > 0) {
			const file = files[0]
			const reader = new FileReader()
			reader.onload = (e) => {
				const data = (e.target as any).result // 获取上传数据
				const workbook = XLSX.read(data, { type: 'binary' }) // 获取excel
				const firstSheetName = workbook.SheetNames[0] // 获取表名
				const worksheet = workbook.Sheets[firstSheetName] // 获取表格中的数据
				const jsonData = XLSX.utils.sheet_to_json(worksheet) // 将数据转为 json

				tableData.value = jsonData
			}
			reader.readAsBinaryString(file)
		}
		return {
			fileInput,
			columns,
			tableData,
			handleUploadClick,
			handleFileChange,
		}
	}
</script>

<style scoped>
	.container {
		width: 100%;
		height: 60px;
		line-height: 60px;
		display: flex;
		justify-content: space-around;
	}

	.upload {
		margin-left: 500px;
	}
</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值