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>
      <input
        type="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-button
            type="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>

注意事项和优化建议

  1. 文件格式支持 :目前只支持 .xlsx 格式,可以根据需求扩展支持 .xls 等其他格式。

  2. 数据验证和处理:在解析和展示数据时,应考虑添加数据验证逻辑,确保数据的完整性和正确性。

  3. 性能优化:如果处理的 Excel 文件较大,可以考虑分批读取和展示数据,以提高性能。

  4. 错误处理:增加更多的错误处理逻辑,提高用户体验。

相关推荐
剑神一笑6 分钟前
CSS 阴影生成器:从单层到多层叠加的艺术
前端·css·css3
lljss202027 分钟前
1. NameServer 域名服务器---NS
linux·服务器·前端
anOnion1 小时前
构建无障碍组件之Tooltip Pattern
前端·html·交互设计
陈随易1 小时前
为什么今天还会有新语言?MoonBit 想解决什么问题?
前端·后端·程序员
西洼工作室1 小时前
unipp+vue3+python h5+app极验验证码集成全流程解析
前端·uni-app·全栈·极验
ZC跨境爬虫1 小时前
跟着 MDN 学 HTML day_15:(媒体缓冲、拖动与时间范围控制)
前端·笔记·ui·html·edge浏览器·媒体
李白的天不白1 小时前
webpack 与 webpack-cli 版本匹配问题
前端·webpack·node.js
tool1 小时前
Hermes Agent 从安装到生产:我的完整踩坑记录
前端
kyriewen111 小时前
奥特曼借GPT-5.5干杯,而你的Copilot正按Token收钱
前端·gpt·ai·copilot
空中海2 小时前
05 React架构设计、项目实践与专家清单
前端·react.js·前端框架