vue+docxtemplater,填充word模板

发布时间 2023-06-01 10:46:09作者: wangyb56

安装依赖

yarn add docxtemplater
yarn add pizzip
yarn add jszip-utils
yarn add file-saver
// 模板解析插件(支持list循环直接使用$index,使用if判断语法)
yarn add angular-expressions
yarn add lodash

页面测试代码

<template>
<div>
<button @click="btnClick">docx</button>
</div>
</template>

<script>
import { exportDocx } from '@/utils/docx.js'
export default {
data() {
return {};
},
computed: {},

mounted() {},

methods: {
btnClick() {
exportDocx(
"/test.docx", // 将模板文件放入这个public静态文件夹中
{ // 生成模板对应的数据格式
value1: "小明同学",
value2: "小明同学",
value3: "小明同学",
value4: "小明同学",
value5: "2022-10-20",
list: [{
value6: "项目名称1",
value7: "项目名称",
value8: "项目名称",
value9: "项目名称",
value10: "项目名称",
value11: "项目名称",
value12: "项目名称",
value13: "项目名称",
value14: "项目名称",
value15: "项目名称",
},
{
value6: "项目名称2",
value7: "项目名称",
value8: "项目名称",
value9: "项目名称",
value10: "项目名称",
value11: "项目名称",
value12: "项目名称",
value13: "项目名称",
value14: "项目名称",
value15: "项目名称",
},
{
value6: "项目名称3",
value7: "项目名称",
value8: "项目名称",
value9: "项目名称",
value10: "项目名称",
value11: "项目名称",
value12: "项目名称",
value13: "项目名称",
value14: "项目名称",
value15: "项目名称",
},
],
},
"测试.docx"
);
},
},
};
</script>
<style scoped>
</style>

新建src→utils→docx.js

import Docxtemplater from 'docxtemplater'
import PizZip from 'pizzip'
import JSZipUtils from 'jszip-utils'
import {
saveAs
} from 'file-saver'

/**
4. 导出docx
5. @param { String } tempDocxPath 模板文件路径
6. @param { Object } data 文件中传入的数据
7. @param { String } fileName 导出文件名称
*/
export const exportDocx = (tempDocxPath, data, fileName) => {
var expressions = require("angular-expressions");
var assign = require("lodash/assign");
var last = require("lodash/last");
expressions.filters.lower = function(input) {
if (!input) return input;
return input.toLowerCase();
};

function angularParser(tag) {
tag = tag
.replace(/^\.$/, "this")
.replace(/(’|‘)/g, "'")
.replace(/(“|”)/g, '"');
const expr = expressions.compile(tag);
return {
get: function(scope, context) {
let obj = {};
const index = last(context.scopePathItem);
const scopeList = context.scopeList;
const num = context.num;
for (let i = 0, len = num + 1; i < len; i++) {
obj = assign(obj, scopeList[i]);
}
obj = assign(obj, {
$index: index
});
return expr(scope, obj);
},
};
}
// 读取并获得模板文件的二进制内容
JSZipUtils.getBinaryContent(tempDocxPath, (error, content) => {
// input.docx是模板。我们在导出的时候,会根据此模板来导出对应的数据
// 抛出异常
if (error) {
this.$message.error("导出word文档失败!");
throw error;
}
// 创建一个JSZip实例,内容为模板的内容
// let zip = new JSZip(content);
let zip = new PizZip(content);
// 创建并加载Docxtemplater实例对象
// let doc = new window.Docxtemplater().loadZip(zip);
let doc = new Docxtemplater()
.loadZip(zip)
.setOptions({
parser: angularParser
});
// 设置模板变量的值
doc.setData(data);
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
}));
this.$message.error("导出word文档失败!");
throw error;
}

// 生成一个代表docxtemplater对象的zip文件(不是一个真实的文件,而是在内存中的表示)
let out = doc.getZip().generate({
type: "blob",
mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
});
// 将目标文件对象保存为目标类型的文件,并命名
saveAs(out, fileName);
});
}

word模板

生成word文件

 

注意:

    • 将模板文件放入这个public静态文件夹中;
    • vue项目导出word,需要用到docxtemplate工具,但是但凡需要循环在创建模板时候以
      {#数组开始} {值} {/数组结束}
    • 生成word后就可以根据自己需求,对文件进行处理;保存、预览或者转换pdf预览等等;