赞
踩
exportWordDocx.js
import JSZipUtils from “jszip-utils”
import Docxtemplater from “docxtemplater”
import {saveAs} from “file-saver”
import PizZip from “pizzip”
const exportWordDocx = (demoUrl, docxData, fileName) => { // 读取并获得模板文件的二进制内容 JSZipUtils.getBinaryContent( demoUrl, function (error, content) { // 抛出异常 if (error) { throw error } // 创建一个PizZip实例,内容为模板的内容 let zip = new PizZip(content) // 创建并加载docxtemplater实例对象 let doc = new Docxtemplater(zip, { linebreaks: true, nullGetter: function () { return "" } }) 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, fileName) } ) }
export default exportWordDocx
使用:
import exportWordDocx from “…/exportWordDocx”
exportWordDocx(baseUrl + “doc/template2.docx”,{
a:‘要替换的字段’.b:‘要替换的字段2’}, ‘文件名称.doc’)
模板文件template2.docx:
{a}{b}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。