使用插件 docxtemplater
有個需求要把訂單導出成word文檔,百度搜了搜node導word的博客真少,無奈硬著頭皮在npm上看英文文檔,找了好幾個輪子最終實驗下docxtemplater深得我心。
要導出的結果
捕獲.PNG
模板文件
捕獲.PNG
根據docxtemplater官網介紹,生成自己的模板文件,接下來就是coding組裝你的數據了
var JSZip = require('jszip');
var Docxtemplater = require('docxtemplater');
var fs = require('fs');
var path = require('path');
var date="你封裝的數據"
var content = fs
.readFileSync(path.resolve("./", file), 'binary');//你的模板文件
var zip = new JSZip(content);
var doc = new Docxtemplater();
doc.loadZip(zip);
doc.setData(
date
);
doc.render()
var buf = doc.getZip()
.generate({type: 'nodebuffer'});
/**
現在 buf 就是生成的文件內容,你可以fs.write()放到本地,也可以
res.writeHead(200, {
"Content-Type": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
'Content-disposition': 'attachment; filename=' + oid + '.docx'
});
res.end(buf)
瀏覽器下載
*/
docxtemplater 導word 你值得擁有