实现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);
相关推荐
RuoyiOffice21 分钟前
SpringBoot3+Vue3 最推荐的开源 OA 系统 2026:流程驱动、资源闭环、多端互通
spring boot·vue3·flowable·oa·协同办公·spring boot 3·开源oa
AZaLEan__34 分钟前
事件循环讲解
javascript
变与不变80635 分钟前
引用类型、内存原理与对象
开发语言·前端·javascript
Highcharts38 分钟前
Highcharts实战讲解|散点图+多项式回归曲线复杂图表示列Demo
javascript·数据可视化
梨想橙汁43 分钟前
Git 常用命令大全:提交、查看日志、版本回退、文件撤销
前端·javascript
mONESY1 小时前
对话一长上下文就爆?LangChain.js Memory 三种淘汰策略(截断 / 总结 / 检索)实战
javascript
雪芽蓝域zzs2 小时前
第三十二节:部门组织管理(el‑tree 组织树
前端·javascript·vue.js
leoZ2312 小时前
第 7 篇:进阶——校验、联动、列表页
开发语言·前端·javascript·vue.js·人工智能·目标检测·ecmascript
VeryCool2 小时前
别吹了,依赖图像识别的GPT‑6 Astra永远快不起来
前端·javascript·aigc
AC赳赳老秦2 小时前
农产品公开数据应用:OpenClaw 抓取农产品价格、产销公开数据,实现农产品行情动态监测
java·c语言·javascript·python·php·deepseek·openclaw