准备环境:
- npm install pizzip
- npm install jszip-utils
- npm install file-saver
- 自己写一个模板样式放到public中
代码
click(){
let docxsrc = 'collectEdit.docx' //引入之前定义好的模板
let docxName = new Date().toLocaleString() + '下载.docx' //下载文章的名字
let obj = {title: "报告标题",time: "时间", content:"内容", href:"链接"}//下载内容
JSziputils.getBinaryContent(docxsrc,(err,data)=>{
if(err){throw err}
let zip = new PizZip(data)
let doc = new docxtemplater(zip,{ //开启配置项
linebreaks:true,
paragraphL:true
})
doc.setData({products: obj)
try{
doc.render()
}catch(err){
throw err
}
let out = doc.getZip().generate({ //创建blob数据源
type:'blob',
mineType:'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
})
saveAs(out,docxName)
})
}
模板样式(任意定制)
成品图