一、安装依赖
1、npm install docxtemplater
2、npm install pizzip
3、npm install jszip-utils
4、npm install file-saver
二、在页面引入
import docxtemplater from 'docxtemplater';
import PizZip from 'pizzip';
import JSZipUtils from 'jszip-utils';
import { saveAs } from 'file-saver';
三、方法
exportWord() {
let _this = this;
// 读取并获得模板文件的二进制内容
JSZipUtils.getBinaryContent("/static/temp.docx", function(error, content) {
// input.docx是模板。我们在导出的时候,会根据此模板来导出对应的数据
// 抛出异常
if (error) {
throw error;
}
// 创建一个PizZip实例,内容为模板的内容
let zip = new PizZip(content);
// 创建并加载docxtemplater实例对象
let doc = new docxtemplater();
doc.loadZip(zip);
// 设置模板变量的值
doc.setData({
time: time,
table: _this.list
});
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;
}
// 生成一个代表docxtemplater对象的zip文件(不是一个真实的文件,而是在内存中的表示)
let out = doc.getZip().generate({
type: "blob",
mimeType:
"application/vnd.openxmlformats-officedocument.wordprocessingml.document"
});
// 将目标文件对象保存为目标类型的文件,并命名
saveAs(out, "test.docx");
});
}
四、设置word模板并放入static目录(vue3放入public目录)
缺点:碰到文本有换行符/n 无法换行