Vue+ElementUi 项目中 将页面内容转为 Word文档下载
需要提前做好的现成模板(魔板个页面基本上相同的内容)-模板内有变量,替换成页面对应的数据
HTML页面:
转换的word
以下是正文
步骤1:安转导入需要的插件
import docxtemplater from ‘docxtemplater’
import PizZip from ‘pizzip’
import JSZipUtils from ‘jszip-utils’
import {saveAs} from ‘file-saver’
步骤2:Word模版绑定变量值
注意:这里的变量是我项目中变量绑定,
如果需要循环,例如:aa:[{baseInfo:“”},{baseInfo:“”},{baseInfo:“”}]
请使用:(#号开头,/ 斜杠结尾)
{#aa}{baseInfo}
{/aa}
步骤3:具体代码
注意点:
1.模板文件使用vue-cli2的时候,放在static目录下。使用vue-cli3的时候,放在public目录下。
2.文件须以docx结尾。
<el-button type="primary" size="medium" @click="downloadWord">
<span class="d-in-block v-mid font-size-16">下载</span>
</el-button>
downloadWord(){
let _this = this;
// 读取并获得模板文件的二进制内容
JSZipUtils.getBinaryContent("../../../../../public/files/01A_jyjwjgs.docx", function (error, content) {
// model.docx是模板。我们在导出的时候,会根据此模板来导出对应的数据
// 抛出异常
if (error) {
throw error;
}
// 创建一个PizZip实例,内容为模板的内容
let zip = new PizZip(content);
// 创建并加载docxtemplater实例对象
let doc = new docxtemplater().loadZip(zip);
// 设置模板变量的值,同步把对应变量绑定到word模板中
let docxData = _this.singleData;//这里的_this.singleData是后台返回的值
// let docxData = {
// gw_zh: "1111",
// gw_title:"我是标题",
// gw_content: "我是内容",
// fb_dateline:"我是时间"
// }
doc.setData({
...docxData
});
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, "模板(Worde)文件下载.docx");
});
}
写在最后: 文章参考 参考1 还有参考2
如果有乡音报错请移步参考2的中下段 可看到问题概述,这里就不搬运了,就写到这里的。