vue3 采用xlsx库实现本地上传excel文件,前端解析为Json数据

发布于:2025-02-22 ⋅ 阅读:(19) ⋅ 点赞:(0)

需求:本地上传excel 文件,但需要对excel 文件的内容进行解析,然后展示出来

1. 安装依赖

首先,确保安装了 xlsx 库:

bash复制

npm install xlsx

2. 创建 Vue 组件

创建一个 Vue 组件(如 ExcelUpload.vue),用于实现文件上传和解析功能。

组件代码:

<template>
  <div>
    <input type="file" class="file-btn hoverPointer" accept=".xls,.xlsx"

                            @change="changeExcel($event)" />
    <div v-if="tableData.length > 0">
      <table>
        <thead>
          <tr>
            <th v-for="header in headers" :key="header">{{ header }}</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(row, index) in tableData" :key="index">
            <td v-for="cell in row" :key="cell">{{ cell }}</td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script>
import { ref } from 'vue';
import * as XLSX from 'xlsx';

export default {
  setup() {
    const headers = ref([]);
    const tableData = ref([]);

    const changeExcel= (event) => {

        const files = e.target.files

        if (files.length <= 0) {

            return false

        } else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {

            console.log('上传格式不正确,请上传xls或者xlsx格式')

            return false

        }

      const reader = new FileReader();
      reader.onload = (e) => {
        const data = e.target.result;
        const workbook = XLSX.read(data, { type: 'binary' });
        const sheetName = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[sheetName];
        const json = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

        headers.value = json[0]; // 表头
        tableData.value = json.slice(1); // 表格数据
      };
      reader.readAsBinaryString(files);
    };

    return {
      headers,
      tableData,
      handleFileUpload,
    };
  },
};
</script>

<style scoped>
table {
  width: 100%;
  border-collapse: collapse;
}
th, td {
  border: 1px solid #ccc;
  padding: 8px;
  text-align: left;
}
</style>

3. 使用组件

在主应用文件(如 App.vue)中引入并使用该组件:

<template>
  <div id="app">
    <ExcelUpload />
  </div>
</template>

<script>
import ExcelUpload from './components/ExcelUpload.vue';

export default {
  name: 'App',
  components: {
    ExcelUpload,
  },
};
</script>

4. 功能说明

  1. 文件上传:通过 <input type="file"> 元素选择 Excel 文件

  2. 文件读取:使用 FileReader 读取文件内容为二进制字符串

  3. 解析为 JSON:使用 xlsx 库将 Excel 数据转换为 JSON 格式 。

  4. 数据展示:将解析后的表头和数据展示在表格中。

5. 扩展功能

  • 错误处理:在文件读取和解析过程中添加错误处理,提示用户文件格式错误或解析失败。

  • 大文件优化:对于大文件,可以分页显示数据或使用异步加载。

  • 自定义解析逻辑:根据实际需求,对数据进行格式转换或校验。

通过以上步骤,你可以在 Vue 3 项目中实现本地上传 Excel 文件并解析为 JSON 数据的功能。