Vue 3 实现 Excel 表格解析的完整指南
在现代 web 开发中,数据导入是一个常见的需求,而 Excel 文件作为数据存储的重要格式之一,能够实现 Excel 表格的解析并展示在前端页面上是一项非常实用的功能。本文将详细介绍如何在 Vue 3 项目中使用 ExcelJS 库来解析 Excel 文件,并将数据展示在表格中。
安装依赖库
npm install exceljs
代码实现
模板部分
<template><div class="addBatchTask-func"><div class="title"><h2>Excel 表格解析 Demo</h2></div><div class="but"><a-button @click="handleUpload" type="primary">上传表格</a-button><inputtype="file"ref="fileInput"style="display: none"@change="handleFileChange"accept=".xlsx"/></div><div class="table-box" v-if="data.length > 0"><a-table :columns="columns" :data-source="data" :pagination="false"><template #bodyCell="{ column, record }"><a-buttontype="primary"@click="handleOk(record)"v-if="column.key === 'action'">删除</a-button></template></a-table></div></div>
</template>
<style lang="less" scoped>
.addBatchTask-func {width: 100%;height: 100vh;.table-box {:deep(.ant-table) {background: black;.ant-table-thead {.ant-table-cell {background: #000;color: #fff;font-size: 14px;font-weight: 600;}}}}
}
</style>
脚本部分
<script setup>
import * as ExcelJS from "exceljs";
import { ref } from "vue";const fileInput = ref(null);const data = ref([]);const columns = [{title: "姓名",dataIndex: "name",key: "name",},{title: "年龄",dataIndex: "age",key: "age",},{title: "性别",dataIndex: "sex",key: "sex",},{title: "家庭住址",dataIndex: "address",key: "address",},{title: "操作",key: "action",},
];// 处理上传文件的事件
const handleUpload = () => {const fileInput = document.querySelector('input[type="file"]');console.log(fileInput, "fileInput");fileInput.value = ""; // 重置文件输入字段的值fileInput.click();
};const handleFileChange = async (event) => {data.value = [];const file = event.target.files[0];console.log(file, "file");if (!file) return;try {const reader = new FileReader();reader.onload = async (e) => {if (!e.target || !e.target.result) {reject("File reading failed");return;}const arrayBuffer = e.target.result;const workbook = new ExcelJS.Workbook();await workbook.xlsx.load(arrayBuffer);const worksheet = workbook.getWorksheet(1);worksheet.eachRow({ includeEmpty: false }, (row, rowNumber) => {if (rowNumber > 1) {const rowData = {key: rowNumber.toString(),name: row.getCell(1).value || "",age: row.getCell(2).value || "",sex: row.getCell(3).value || "",address: row.getCell(4).value || "",};console.log(rowData, "rowData");data.value.push(rowData);}});};reader.onerror = (error) => {console.log(error);};reader.readAsArrayBuffer(file);} catch (error) {console.error("Error importing table:", error);}
};
</script>
注意事项和优化建议
-
文件格式支持:目前只支持
.xlsx
格式,可以根据需求扩展支持.xls
等其他格式。 -
数据验证和处理:在解析和展示数据时,应考虑添加数据验证逻辑,确保数据的完整性和正确性。
-
性能优化:如果处理的 Excel 文件较大,可以考虑分批读取和展示数据,以提高性能。
-
错误处理:增加更多的错误处理逻辑,提高用户体验。