- 安装必要的库
npm install xlsx
- 创建一个组件来处理文件上传和解析:
在src/components
目录下创建一个名为ExcelPreview.vue
的文件<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 示例:// 为了解决跨域问题,在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
文件中: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);