vue预览word文档

334 阅读1分钟

本文将介绍如何使用vue-office来预览word文档,它支持多种文件(docx、pdf、excel)预览的vue组件套装,支持vue2/3。

安装

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

使用实例

文档预览场景大致可以分为两种: 有文档网络地址,比如 https://***.docx 文件上传时预览,此时可以获取文件的ArrayBuffer或Blob

docx文档的预览

这里主要介绍如何使用文件的blob来预览,(因为上一节介绍了通过easy-poi来导出word文档)。我这里使用的vue组件库是antdv,如何你使用的是其他的可以对相关的进行替换

<template>
  <a-button @click="handlePreview" :loading="loading">导出文档</a-button>
  <a-drawer
      v-model:open="open"
      class="custom-class"
      width="80%"
      root-class-name="root-class-name"
      :root-style="{ color: 'blue' }"
      style="color: red"
      title="预览"
      placement="right"
      @after-open-change="afterOpenChange"
  >
    <template #extra>
      <a-button style="margin-right: 8px" @click="handleDownload">下载</a-button>
    </template>
    <vue-office-docx :src="docx" @rendered="rendered"/>
  </a-drawer>
</template>
<script setup>
//引入VueOfficeDocx组件
import VueOfficeDocx from '@vue-office/docx'
//引入相关样式
import '@vue-office/docx/lib/index.css'
import {exportWord} from "@/api/exportWord/index.js";
import {ref} from "vue";

const docx = ref('')
const open = ref(false)
const loading = ref(false)
const handlePreview = () => {
  loading.value = true
  exportWord({}).then(res => {
    const url = window.URL.createObjectURL(new Blob([res], {type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'}));
    docx.value = url;
    open.value = true
  }).finally(() => {
    loading.value = false
  })
}

const rendered = () => {
  console.log('rendered')
}

const afterOpenChange = () => {
  console.log('afterOpenChange')
}

const handleDownload = () => {
  // 获取该word文档并下载
  const link = document.createElement('a');
  link.href = docx.value;
  link.setAttribute('download', 'export.docx'); // 设置下载文件名
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}
</script>
<style scoped>
:deep(.docx-wrapper) {
  background-color: #ffffff;
}

:deep(.docx) {
  width: 100% !important;
}
</style>

import {exportWord} from "@/api/exportWord/index.js";引入的是向后端发生请求接口:(注意这里一定要配置responseType: 'blob')

import http from "@/utils/server/http.js";

export const exportWord = (data) => {
    return http.post('/exportWord', data, {responseType: 'blob'})
}

实际预览的效果

在这里插入图片描述

总结

使用vue- Office,可以非常的简单的去预览word文档。 如果你有任何问题或建议,欢迎留言交流!