在 Vue 3 项目中实现 Excel 表格在线预览。
**使用 @vue-office/excel(支持 .xlsx/.xls)**
该库专为 Vue 3 设计,支持 Word、Excel、PPT、PDF 等多种格式,集成简单、样式保留较好。
安装依赖
npm install @vue-office/excel @vue-office/docx @vue-office/pptx @vue-office/pdf
引入样式(重要)
import '@vue-office/excel/lib/index.css'
使用组件
<template>
<div class="file-preview-container">
<VueOfficeExcel
v-if="['xlsx', 'xls'].includes(fileType)"
:src="fileSrc"
:style="{ width: '100%', height: '600px', border: '1px solid #e8e8e8' }"
@rendered="handleRendered"
@error="handleError"
/>
</div>
</template><script setup>
import { ref, computed } from 'vue'
import VueOfficeExcel from '@vue-office/excel'const props = defineProps({
src: String // 可为 URL、Blob、File 或 ArrayBuffer
})const fileSrc = ref(props.src)
const fileType = computed(() => {
if (!props.src) return ''
const filename = typeof props.src === 'string' ? props.src.toLowerCase() : props.src.name?.toLowerCase()
if (filename.endsWith('.xlsx')) return 'xlsx'
if (filename.endsWith('.xls')) return 'xls'
return ''
})const handleRendered = () => console.log('Excel 渲染完成')
const handleError = (err) => console.error('渲染失败:', err)
</script>
✅ 优点:支持 .xls 和 .xlsx,保留原始样式,无需手动解析。
⚠️ 注意:需确保文件来源支持跨域,或通过后端代理获取二进制流 27。