1 public下面新建word文檔欲逃,填入Hi???{nickName}丧叽,nickName是字段名稱骚灸,在需要導(dǎo)出word文檔的界面定義
obj:{
nickName:"師太"
}
2 安裝命令
npm?install?docxtemplater?pizzip
npm?install?jszip-utils?--save
npm?install?jszip?--save
npm?install?file-saver?--save
3 在需要導(dǎo)出word文檔的頁(yè)面引入
import?Docxtemplater?from?'docxtemplater';
import?{?saveAs?}?from?'file-saver';
import?JSZip?from?'jszip';
import?JSZipUtils?from?'jszip-utils';
4 編寫(xiě)點(diǎn)擊事件
let _this = this;
//1.docx,要和自己定義的文檔名稱保持一致
JSZipUtils.getBinaryContent('1.docx', function(error, content) {
// input.docx是模板驴一。我們?cè)趯?dǎo)出的時(shí)候休雌,會(huì)根據(jù)此模板來(lái)導(dǎo)出對(duì)應(yīng)的數(shù)據(jù)
// 拋出異常
if (error) {
throw error;
}
// 創(chuàng)建一個(gè)JSZip實(shí)例,內(nèi)容為模板的內(nèi)容
let zip = new JSZip(content);
// 創(chuàng)建并加載docxtemplater實(shí)例對(duì)象
let doc = new Docxtemplater();
doc.loadZip(zip);
// 設(shè)置模板變量的值
doc.setData({..._this.obj,});
// 用模板變量的值替換所有模板變量
try {doc.render()} catch (error) {
// 拋出異常
let e =?
{message: error.message,name: error.name,stack: error.stack,properties: error.properties};
throw error}
// 生成一個(gè)代表docxtemplater對(duì)象的zip文件(不是一個(gè)真實(shí)的文件肝断,而是在內(nèi)存中的表示)
let out = doc.getZip().generate({
type: 'blob',
mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
});
// 將目標(biāo)文件對(duì)象保存為目標(biāo)類型的文件杈曲,并命名
saveAs(out, _this.obj.nickName + '的簡(jiǎn)介.docx');
});