当前位置:   article > 正文

导出word模板开发记录

导出word模板开发记录

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)
		}
	)
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49

export default exportWordDocx

使用:
import exportWordDocx from “…/exportWordDocx”

exportWordDocx(baseUrl + “doc/template2.docx”,{
a:‘要替换的字段’.b:‘要替换的字段2’}, ‘文件名称.doc’)

模板文件template2.docx:
{a}{b}

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/正经夜光杯/article/detail/783728
推荐阅读
  

闽ICP备14008679号