前提:本次示例基于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>