在Vue3中生成動態(tài)的word文檔的示例代碼
需求
在開發(fā)過程中遇到一個需求,動態(tài)生成一個word報表,當時考慮了是前端做還是后端做的問題,最后發(fā)現(xiàn)兩個解決需求的方法都大差不差,但考慮到前端少發(fā)一個請求,就此使用的前端來解決。
首先,我們需要安裝以下幾個庫:
npm i docxtemplater 是一個用于基于模板生成動態(tài) `.docx` 文檔的 JavaScript 庫。它允許你將動態(tài)數(shù)據(jù)填充到 `.docx` 模板文件中
npm i jszip-utils 用于在瀏覽器中處理 ZIP 文件的工具庫
npm file-saver 是一個用于在瀏覽器中保存文件的 JavaScript 庫
創(chuàng)建一個工具函數(shù),用于加載 .docx 模板,填充數(shù)據(jù)并生成文檔。
//引入工具
import PizZip from 'pizzip';
import Docxtemplater from 'docxtemplater';
import JSZipUtils from 'jszip-utils';
import { saveAs } from 'file-saver';
// 加載 .docx 模板文件
function loadFile(url, callback) {
JSZipUtils.getBinaryContent(url, callback);
}
// 下載生成的文檔
export function download(file, name) {
saveAs(file, name);
}
// 生成并下載 Word 文檔(templatePath是word文檔模版地址,data是對應(yīng)的數(shù)據(jù))
export function generateWordDocument(templatePath, data) {
return new Promise((resolve, reject) => {
loadFile(templatePath, function (error, content) {
if (error) {
reject(new Error(`Error loading template file: ${error.message}`));
return;
}
try {
// 加載模板文件內(nèi)容到 PizZip
const zip = new PizZip(content);
const doc = new Docxtemplater(zip, {
paragraphLoop: true,
linebreaks: true,
});
// 設(shè)置模板中的占位符數(shù)據(jù)
doc.setData(data);
// 渲染文檔
doc.render();
// 生成最終的文檔 Blob
const fileWord = doc.getZip().generate({
type: 'blob',
mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
});
// 返回生成的文檔 Blob
resolve(fileWord);
} catch (error) {
console.error('Error rendering document:', error);
reject(new Error(`Error rendering document: ${error.message}`));
}
});
});
}
在需要的組件內(nèi)調(diào)用
<template>
<div>
<button @click="startGeneration">生成文檔</button> <button @click="downloadWord" :disabled="!generatedFile">下載文檔</button>
</div>
</template>
<script setup>
import { ref } from 'vue';
import { generateWordDocument, download } from '../utils/wordGenerate.js';
const generatedFile = ref(null);
// 模板文件的路徑,一般放在 public 目錄中
const templatePath = '/template.docx';
const data = { name: '測試', date: '2024-09-23' };
const startGeneration = async () => {
try {
generatedFile.value = await generateWordDocument(templatePath, data);
console.log('文檔生成成功');
} catch (error){
console.error('Error generating document:', error);
}
};
//文檔下載
const downloadWord = () => {
if (generatedFile.value) {
download(generatedFile.value, 'generated-document.docx');
} else {
console.error('No file generated');
}};
</script>
就此功能完成了,當然如果需求是生成成功的同時就下載文檔,可以將下載功能直接寫在生成功能內(nèi),就可以省去異步處理的代碼量。
到此這篇關(guān)于在Vue3中生成動態(tài)的word文檔的示例代碼的文章就介紹到這了,更多相關(guān)Vue3生成動態(tài)word內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue關(guān)于this.$refs.tabs.refreshs()刷新組件方式
這篇文章主要介紹了vue關(guān)于this.$refs.tabs.refreshs()刷新組件方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03
vue parseHTML函數(shù)源碼解析 AST預(yù)備知識
這篇文章主要為大家介紹了vue parseHTML函數(shù)源碼解析 AST預(yù)備知識示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-07-07

