前端實現docx文件預覽的3種方式舉例及分析
更新時間:2025年03月06日 08:44:09 作者:英子的搬磚日志
這篇文章主要介紹了前端實現docx文件預覽的3種方式,三種方式分別是docx-preview、vue-office和mammoth,文中給出了詳細的代碼示例,需要的朋友可以參考下
需求:
有一個docx文件,需要按其本身的格式,將內容展示出來,即:實現doc文件預覽。
本文將doc文件存放到前端項目的public目錄下

1、docx-preview 實現(推薦)
安裝命令 npm install docx-preview

實現代碼
<template>
<div class="document-wrapper">
<div class="content" ref="contentRef"></div>
</div>
</template>
<script lang="ts" setup>
import { ref } from "vue";
import axios from "axios";
import { renderAsync } from 'docx-preview';
const contentRef = ref<any>(null);
function getDocxContent() {
// 注意:如果是前端本地靜態(tài)文件,需要放放在public目錄下
axios.get('/test.docx', { responseType: 'arraybuffer' }).then((res) => {
renderAsync(res.data, contentRef.value);
}).catch((err) => { console.log(err) })
}
getDocxContent();
</script>
<style lang="less">
.document-wrapper {
margin: 10px;
}
// 設置word文檔的樣式
// .docx-wrapper {
// background: white !important;
// border: 1px solid red;
// section {
// width: 100% !important;
// padding: 20px !important;
// }
// .docx {
// box-shadow: none !important;
// }
// }</style>
效果: 樣式還原度一般,無分頁

2、vue-office 實現
vue-office特點:
- 一站式:提供word(.docx)、pdf、excel(.xlsx, .xls)、ppt(.pptx)多種文檔的在線預覽方案。
- 簡單:只需提供文檔的src(網絡地址)即可完成文檔預覽。
- 體驗好:選擇每個文檔的最佳預覽方案,保證用戶體驗和性能都達到最佳狀態(tài)。
- 性能好:針對數據量較大做了優(yōu)化。
安裝命令
# docx文檔預覽,基于docx-preview庫實現 npm install @vue-office/docx # excel文檔預覽,基于exceljs和x-data-spreadsheet實現,全網樣式支持更好 npm install @vue-office/excel # pdf文檔預覽,基于pdfjs庫實現,實現了虛擬列表增加性能 npm install @vue-office/pdf # pptx文檔預覽,基于pptx-preview實現 npm install @vue-office/pptx
本文只針對word文檔,安裝好如下:

實現代碼
<template>
<div class="document-wrapper">
<VueOfficeDocx :src="fileData" />
</div>
</template>
<script lang="ts" setup>
import { ref } from "vue";
import axios from "axios";
import VueOfficeDocx from '@vue-office/docx'
const fileData = ref<any>(null);
function getDocxContent() {
// 注意:本地靜態(tài)文件需要放放在public目錄下
axios.get('/test.docx', { responseType: 'arraybuffer' }).then((res) => {
fileData.value = res.data;
}).catch((err) => { console.log(err) })
}
getDocxContent();
</script>
<style lang="less">
.document-wrapper {
margin: 10px;
}
</style>
效果: 同第一種方式實現的效果

3、mammoth 實現(不推薦)
安裝命令:npm install mammoth

實現代碼
<template>
<div class="document-wrapper">
<div ref="docxPreviewRef" v-html="fileContent"></div>
</div>
</template>
<script lang="ts" setup>
import { ref } from "vue";
import axios from "axios";
import mammoth from 'mammoth';
const fileContent = ref<any>(null);
function getDocxContent() {
axios.get('/test.docx', { responseType: 'arraybuffer' }).then((res) => {
mammoth.convertToHtml({ arrayBuffer: new Uint8Array(res.data) }).then((res) => {
fileContent.value = res.value;
})
}).catch((err) => { console.log(err) })
}
getDocxContent();
</script>
<style lang="less">
.document-wrapper {
margin: 10px;
}
</style>
效果: word文檔的樣式沒有了,所以不推薦直接使用此中方式預覽.docx文件

總結
到此這篇關于前端實現docx文件預覽的3種方式的文章就介紹到這了,更多相關前端實現docx文件預覽內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

