前端word,Excel在线预览vue-office组件来了

13,154 阅读2分钟

前言

已经上线两年的项目,运营对EOA审批附件查看问题,运营部同事每次都要先下载到本地再预览导致本地下载了大量附件,为了解决以上需求开发了在线预览功能

image.png

vue-office简介

vue-office是一个支持多种文件(docx、.xlsx、pdf)预览的vue组件库,支持vue2和vue3。 目标是成为使用最简单,功能最强大的文件预览库。

功能特点

一站式提供docx、.xlsx、pdf多种文档的在线预览方案,有它就够了,不用再四处寻找、测试、集成各种库了

使用简单只需提供文档的src(网络地址)即可完成文档预览,也支持ArrayBuffer、Blob等多种格式

支持样式不仅能预览内容,也支持文档样式,最大限度还原office文件内容 只需提供文档的src(网络地址)即可完成文档预览,也支持ArrayBuffer、Blob等多种格式`

安装步骤

#docx文档预览组件
npm install @vue-office/docx vue-demi

#excel文档预览组件
npm install @vue-office/excel vue-demi

#pdf文档预览组件
npm install @vue-office/pdf vue-demi

如果是vue2.6版本或以下还需要额外安装 @vue/composition-api

npm install @vue/composition-api

demo

<template>
    <vue-office-docx
        v-if="currentAttachment.type === 'docx'"
        :src="docx"
        style="height: 100vh;"
        @rendered="renderedHandler"
        @error="errorHandler"
    />
     <iframe v-if="currentAttachment.type === 'pdf'" style="width:100%;height:100%;" :src=pdf" frameborder="0"></iframe>
    <vue-office-excel
        :src="excel"
        v-if="currentAttachment.type === 'xls'"
        style="height: 100vh;"
        @rendered="renderedHandler"
        @error="errorHandler"
    />
</template>

<script>
//引入VueOfficeDocx组件
import VueOfficeDocx from '@vue-office/docx'
import VueOfficeExcel from '@vue-office/excel'

//引入相关样式
import '@vue-office/docx/lib/index.css'
import '@vue-office/excel/lib/index.css'


export default {
    components: {
        VueOfficeDocx,
        VueOfficeExcel
    },
    data() {
        return {
            docx: 'http://xxx.com/test6.docx', //设置文档网络地址,可以是相对地址
            excel: 'http://xxx.com/test3.xls', //设置文档网络地址,可以是相对地址
            pdf: 'http://xxx.com/test1.pdf'

        }
    },
    methods: {
        renderedHandler() {
            console.log("渲染完成")
        },
        errorHandler() {
            console.log("渲染失败")
        }
    }
}
</script>

我这里没有用pdf组件,这个vue-office组件好处就是可以单独引用,pdf预览我这边用的iframe这就满足需求了。

注意

word 只支持docx后缀文件

官方文档