首先导出word文档 方式 传送门这里面讲的很详细。不过,如果你复制就是出现两个问题。现在我就把问题和解决方法说明一下。
第一个:word 模板一定要放在:
1.模板文件使用vue-cli2的时候,放在static目录下。使用vue-cli3的时候,放在public目录下。
2.文件须以docx结尾。
不然一直报这不是zip文件的错误
第二个:模板变量问题,
表格内容数据需要使用 {#参数名}开始 {/参数名} 结尾
这个就是我模板变量。
注意 模板中的 jyfiqd 对应下面函数中data的变量名*
第三个,这个是我修改后的封装函数。替换一下就好了
export const exportDocx = (tempDocxPath, data, fileName) => {
// 读取并获得模板文件的二进制内容
JSZipUtils.getBinaryContent(tempDocxPath, (error, content) => {
if (error) {
throw error;
}
let zip = new PizZip(content);
let doc = new docxtemplater().loadZip(zip);
let docxData = {//数据处理 这里是变量名想设置什么就设置什么
jyfjqd: data,
};
doc.setData({
...docxData
});
try {
// render the document (replace all occurences of {first_name} by John, {last_name} by Doe, ...)
doc.render();
} catch (error) {
let e = {
message: error.message,
name: error.name,
stack: error.stack,
properties: error.properties,
};
console.log({
error: e
});
// The error thrown here contains additional information when logged with JSON.stringify (it contains a property object).
throw error;
}
let out = doc.getZip().generate({
type: "blob",
mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
}); //Output the document using Data-URI
saveAs(out, fileName);
});
};