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