1.安裝依賴
npm i docxtemplater -S
npm i docxtemplater-image-module -S
npm i pizzip -S
npm i jszip-utils -S
npm i file-saver -S
2.vue文件引入依賴
import docxtemplater from "docxtemplater";
import PizZip from "pizzip";
import JSZipUtils from "jszip-utils";
import { saveAs } from "file-saver";
import ImageModule from "docxtemplater-image-module";
3.vue需要實現的方法
export default {
data() {
let self = this;
return {
imageOpts: {
getImage(tagValue, tagName) { //獲取base64格式圖片
return self.base64DataURLToArrayBuffer(tagValue);
},
getSize(img, tagValue, tagName) { //返回圖片大小,長*寬
return [60, 80];
}
}
}
},
methods: {
//導出文件
export2Word(v, t, name) { //v:圖片路徑,t:時間字符串,name:導出文件名稱--變量需自己定制,此處為舉例
let self = this;
JSZipUtils.getBinaryContent(
"***.docx", //需要導出的模板文件地址
function(error, content) {
if (error) {
throw error;
}
let zip = new PizZip(content);
let doc = new docxtemplater().loadZip(zip);
doc.attachModule(new ImageModule(self.imageOpts));
doc.setData({ //設置模板數據
imgsrc: v,
timestr: t
});
try {
doc.render();
} catch (error) {
let e = {
message: error.message,
name: error.name,
stack: error.stack,
properties: error.properties
};
console.log(JSON.stringify({ error: e }));
throw error;
}
let out = doc.getZip().generate({
type: "blob",
mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document" //導出文件格式
});
saveAs(out, name + ".docx");
}
);
},
//獲取base64格式圖片
base64DataURLToArrayBuffer(dataURL) {
const base64Regex = /^data:image\/(png|jpg|svg|svg);base64,/;
if (!base64Regex.test(dataURL)) {
return false;
}
const stringBase64 = dataURL.replace(base64Regex, "");
let binaryString;
if (typeof window !== "undefined") {
binaryString = window.atob(stringBase64);
} else {
binaryString = Buffer.from(stringBase64, "base64").toString("binary");
}
const len = binaryString.length;
const bytes = new Uint8Array(len);
for (let i = 0; i < len; i++) {
const ascii = binaryString.charCodeAt(i);
bytes[i] = ascii;
}
return bytes.buffer;
}
}
}
4.導出文件

5.模板說明
{%img} 圖片
{#list}{/list} 循環、if判斷
{#list}{/list}{^list}{/list} if else
{str} 文字
詳見:https://docxtemplater.readthedocs.io/en/latest/tag_types.html
6.注
引入依賴時,使用 npm i,不要使用 cnpm i