实现Vue3/Nuxt3 预览excel文件

  1. 安装必要的库

    复制代码
    npm install xlsx
  2. 创建一个组件来处理文件上传和解析
    src/components 目录下创建一个名为 ExcelPreview.vue 的文件

    javascript 复制代码
    <template>
    <div>
    <input type="file" @change="handleFileUpload" />
    <table v-if="sheetData.length">
    <thead><tr><th v-for="(header, index) in sheetData[0]" :key="index">{{ header }}</th></tr></thead>
    <tbody><tr v-for="(row, rowIndex) in sheetData.slice(1)" :key="rowIndex"><td v-for="(cell, cellIndex) in row" :key="cellIndex">{{ cell }}</td></tr></tbody>
    </table>
    </div>
    </template>
    
    <script setup lang="ts">
    import { ref } from 'vue';
    import * as XLSX from 'xlsx';
    
    const sheetData = ref([]);
    
    const handleFileUpload = (event: Event) => {
      const file = (event.target as HTMLInputElement).files?.[0];
      if (file) {
        const reader = new FileReader();
        reader.onload = (e) => {
          const data = new Uint8Array(e.target?.result as ArrayBuffer);
          const workbook = XLSX.read(data, { type: 'array' });
          const firstSheetName = workbook.SheetNames[0];
          const worksheet = workbook.Sheets[firstSheetName];
          sheetData.value = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
        };
        reader.readAsArrayBuffer(file);
      }
    };
    </script>

    如果excel文件是后台返回的一个链接,需要重新请求解析成ArrayBuffer,

    以下是nuxt3 示例:

    javascript 复制代码
    // 为了解决跨域问题,在server/api 下 创建一个请求api, downloadFileByProxy.ts
    import { defineEventHandler } from 'h3';
    
    export default defineEventHandler(async event => {
      const { filePath } =  getQuery(event);
      let matches = filePath?.match(/^https?\:\/\/([^\/?#]+)(?:[\/?#]|$)/i);
      let domain = matches && matches[1]; 
      return proxyRequest(event,`https://${domain}/`, {
        fetch: ()=>fetch(filePath),
      })
    })

    ExcelPreview.vue 文件中:

    javascript 复制代码
      async function getFile(path: string) {
        // download pdf from api to prevent CORS
        const { _data } = await $fetch.raw(`/api/downloadFileByProxy`, {
          method: 'get',
          params: {
            filePath: path,
          },
        });
        let blob = _data;
        let buffer = await blob?.arrayBuffer();
        return buffer;
      }
    
      const debounceRenderHandle = debounce(async () => {
        bufferCache.value = bufferCache.value || (await getFile(props.path)); // bufferCache这里是用来处理缓存,可以视具体情况加这个变量与否
        const data = new Uint8Array(bufferCache.value as ArrayBuffer);
        const workbook = XLSX.read(data, { type: 'array' });
        const firstSheetName = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[firstSheetName];
        sheetData.value = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
      }, 500);
相关推荐
张元清2 小时前
React useDebounce Hook:给状态和回调做防抖(2026)
javascript·react.js
Cobyte3 小时前
21.Vue Vapor 组件的实现原理
前端·javascript·vue.js
铁皮饭盒3 小时前
Rust版Bun1.4之前, 盘点Bun1.3新特性
前端·javascript·后端
晓得迷路了3 小时前
栗子前端技术周刊第 135 期 - Vite 8.1、Rspack 2.1、Babel 8.0...
前端·javascript·vite
To_OC12 小时前
LC 207 课程表:刚学图论那会儿,我连这是拓扑排序都没看出来
javascript·算法·leetcode
To_OC12 小时前
LC 208 实现 Trie 前缀树:曾被名字劝退,写完发现是送分题
javascript·算法·leetcode
天渺工作室12 小时前
实现一个adblock/adblock plus等浏览器广告拦截器检测插件
前端·javascript
kyriewen20 小时前
2026 年了,还在用 Node.js?Bun 迁移实战:20 分钟搞定,附踩坑记录
前端·javascript·node.js
minglie1 天前
一个置换问题
javascript
默_笙1 天前
🌀 别再手动写 Prompt 了!我让 AI 自己循环改到满意为止
javascript