操作步驟
1湾趾、安裝插件
-- 安裝 docxtemplater
cnpm install docxtemplater pizzip? --save
-- 安裝 jszip-utils
cnpm install jszip-utils --save
-- 安裝 jszip
cnpm install jszip --save
-- 安裝 FileSaver
cnpm install file-saver --save
2巧娱、在需要的組件中引入
import jszip from 'jszip'
import jszip_utilsfrom 'jszip-utils'
import docxtemplater from 'docxtemplater'
import FileSaver from 'file-saver'
3亿虽、創(chuàng)建模板文件
首先創(chuàng)建一個(gè)模板文件性雄,事先定義好格式和內(nèi)容迎膜。docxtemplater 之前介紹到是通過(guò)標(biāo)簽的形式來(lái)填充數(shù)據(jù)的伴栓,簡(jiǎn)單的數(shù)據(jù)我們可以使用{} + 變量名來(lái)實(shí)現(xiàn)簡(jiǎn)單的文本替換诬辈。
① 文本替換
定義模板
test {name}
數(shù)據(jù)定義
{"name":"hello"}
輸出效果
test hello
② 循環(huán)輸出
定義模板
{#table}
{name},{age}
{/table}
定義數(shù)據(jù)
{
"data":[
? ? {"name":"張三","age":18},
? ? {"name":"李祀","age":28},
]
}
輸出效果
張三混弥,18
李祀趴乡,28
ps:使用時(shí)將data對(duì)應(yīng)的數(shù)據(jù)賦值給table
pps:整體循環(huán)輸出多張表格時(shí),將循環(huán)的位置設(shè)置在表格之外蝗拿,示例如下
將寫(xiě)好的模板放在目錄下晾捏,筆者放在public/outsideExample.docx下
4、使用
①讀取模板內(nèi)容
②裝載到zip對(duì)象中
③設(shè)置文件數(shù)據(jù)
④生成文件
⑤保存文件
代碼:
jszip_utils.getBinaryContent("outsideExample.docx",function(error, content) {
// outsideExample.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)容
? ? var zip =new jszip(content);
// 創(chuàng)建并加載docxtemplater實(shí)例對(duì)象
? ? var doc =new window.docxtemplater().loadZip(zip);
// 設(shè)置模板變量的值
? ? doc.setData({
table:data
? ? })
try {
// 用模板變量的值替換所有模板變量
? ? ? ? doc.render();
}catch (error) {
// 拋出異常
? ? ? ? var e = {
message: error.message,
name: error.name,
stack: error.stack,
properties: error.properties
? ? ? ? };
console.log(JSON.stringify({error:e }));
throw error;
}
// 生成一個(gè)代表docxtemplater對(duì)象的zip文件(不是一個(gè)真實(shí)的文件仓手,而是在內(nèi)存中的表示)
? ? var out =doc.getZip().generate({
type:"blob",
mimeType:
"application/vnd.openxmlformats-officedocument.wordprocessingml.document"
? ? });
// 將目標(biāo)文件對(duì)象保存為目標(biāo)類(lèi)型的文件胖齐,并命名
? ? FileSaver.saveAs(out,"文件名.docx");
});
9-4 更新
模板定義中判斷語(yǔ)句的寫(xiě)法:{#name}{name}{/name}