实现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);
相关推荐
十一.366几秒前
83-84 包装类,字符串的方法
前端·javascript·vue.js
over69713 分钟前
深入解析:基于 Vue 3 与 DeepSeek API 构建流式大模型聊天应用的完整实现
前端·javascript·面试
接着奏乐接着舞34 分钟前
react useMeno useCallback
前端·javascript·react.js
码农阿豪39 分钟前
Vue项目构建中ESLint的“换行符战争”:从报错到优雅解决
前端·javascript·vue.js
韩曙亮1 小时前
【Web APIs】BOM 浏览器对象模型 ⑥ ( location 对象 | location 常用属性和方法 | URL 简介 )
前端·javascript·dom·url·bom·location·浏览器对象模型
春生野草2 小时前
Ruoyi前端基于vue的脚手架的目录解析
前端·javascript·vue.js
yivifu2 小时前
Excel表格取多行数据中的唯一值及多条件数据查询问题
excel
m0_740043732 小时前
Axios拦截器 -- 请求拦截器和响应拦截器
开发语言·前端·javascript
风止何安啊3 小时前
递归 VS 动态规划:从 “无限套娃计算器” 到 “积木式解题神器”
前端·javascript·算法
GPTMirrors镜像系统3 小时前
JS 实现指定 UA 访问网站跳转弹窗提醒,解决夸克等浏览器兼容性问题
前端·javascript