Vue在线预览Excel和Docx格式文件
前提:本次示例基于Vue2.x,所用插件为Vue-Office。
一、Vue-Office 插件简介
Vue-Office 是一个一站式解决方案,支持多种 Office 文件格式的在线预览,包括:
Word
(.docx)Excel
(.xlsx、.xls)PDF
PowerPoint
(.pptx)
它适用于 Vue 2 和 Vue 3,同时兼容非 Vue 框架(如 React),为开发者提供了简单、高效的文档预览功能。
二、功能特点
1. 简单集成:
无需为不同文件类型寻找多个库,Vue-Office 提供了统一的预览功能,只需提供文档的 URL(网络地址)即可完成预览,降低开发成本。
2. 良好的用户体验:
针对每种文件类型选择了最佳的预览方案,确保加载速度、渲染效果和交互操作流畅。
3. 性能优化:
针对数据量较大的文档进行了优化,确保在高负载情况下也能保持稳定的预览效果。
4. 支持多种文件格式:
除了常见的 Word、Excel 和 PDF,还支持 PowerPoint 文件。
三、应用示例
1.安装Vue-Office相关组件
npm install @vue-office/excelnpm install @vue-office/docx
2.vue使用
以下以Excel和Word格式文件为例:
<template><div ref="officeViewerRef" v-if="officeDialog" class="officeDemo"><vue-office-excelv-if="xlsxDialog":src="url"style="height: 100vh;"@rendered="renderedHandler"@error="errorHandler"/><vue-office-docxv-if="docxDialog":src="url"style="height: 100vh;"@rendered="renderedHandler"@error="errorHandler"/></div>
</template><script>import VueOfficeExcel from '@vue-office/excel'import '@vue-office/excel/lib/index.css'import VueOfficeDocx from '@vue-office/docx'import '@vue-office/docx/lib/index.css'export default {name: "office-viewer",components: {VueOfficeExcel,VueOfficeDocx,},data(){return {officeLoading: '',xlsxDialog:false,docxDialog:false,url:'',fjType:'',isEnd:false,officeDialog:true,}},watch: {isEnd() {this.officeDialog = false;this.$nextTick(()=>{this.officeDialog = true;})},},mounted(){this.loadFile();},methods: {loadFile(){const url ='实际文件地址';if(url.indexOf(".doc") > -1){this.fjType = 'word';}else{this.fjType = 'excel';}this.url = url;this.officeLoading = this.$loading({lock: true,target:this.$refs.officeViewerRef.$el,text: '正在加载,请稍后....',spinner: 'el-icon-loading',background: 'rgba(0, 0, 0, 0.7)'});if(this.fjType == 'excel'){this.xlsxDialog = true;}else if(this.fjType == 'word'){this.docxDialog = true;}},renderedHandler() {// this.$message.success("渲染完成!");this.officeLoading && this.officeLoading.close();if(this.fjType == 'excel'){this.isEnd = true;}},errorHandler() {this.$message.error("渲染失败!");this.officeLoading && this.officeLoading.close();},}}
</script><style lang="scss">
.officeDemo{background-color: #808080;height: 100%;padding: 30px 0;.vue-office-docx,.vue-office-excel{height: calc(100% - 60px)!important;}.vue-office-excel{width: calc(100% - 60px);margin-left: 30px;}.docx-wrapper{padding-top: 0!important;padding-bottom: 0!important;}.docx{border-radius: 3px;}.docx:last-child{margin-bottom: 0!important;}.x-spreadsheet{padding-top: 5px;box-sizing: border-box;border-radius: 5px;}
}
</style>