docxtemplater 根据数据导出word

下载对应插件

npm i docxtemplater;
npm i pizzip;
npm i file-saver
npm i jszip-utils

创建js文件并引入
import JSZipUtils from "jszip-utils";
import docxtemplater from "docxtemplater";
import { saveAs } from "file-saver";
import PizZip from "pizzip";

export const exportWordDocx = (demoUrl, docxData, fileName) => {
    // 读取并获得模板文件的二进制内容
    console.log(docxData)
    JSZipUtils.getBinaryContent(
        demoUrl,
        function (error, content) {
            // 抛出异常
            if (error) {
                throw error;
            }

            // 创建一个PizZip实例,内容为模板的内容
            let zip = new PizZip(content);
            // 创建并加载docxtemplater实例对象
            let doc = new docxtemplater().loadZip(zip);
            // 去除未定义值所显示的undefined
            doc.setOptions({
                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);
        }
    );
}

指定html文件中引入js
import { xxx } from './xxx'

具体使用
let person = {
  xxx: 'xx'
}
xxx('test.docx', person, 'lst')
(参数1为导入的模板word) (参数2为定义的具体数据) (参数3为导出的文件名称)
test.docx 在vue中放在public目录下面. 名称自己定义要匹配上

word文档使用说明数据对比
指定对象比如 
js数据为 name: '张三'
wodr中
{name}  即可

循环list 列表数据
js数据为  list: [
  { name: '张三', number: 33 },
  { name: '张四', number: 34 },
  { name: '张五', number: 35 },
]
word中
{#list}{name}{number}{/}
以#开始.申明数组名称 具体对应每一项 从name开始 list不占位 结束要/

---------------------------------------------------------------------------
如果需要图片. 图片必须为64格式. 建议配合后端. 避免安全问题

import Docxtemplater from 'docxtemplater'
import ImageModule from 'docxtemplater-image-module-free' //需要图片就导入
import PizZip from 'pizzip'
import JSZipUtils from 'jszip-utils'
import { saveAs } from 'file-saver'

export function exportWordAndImage(report) {
	var templateChose = '测试.docx' //模板推荐放在public文件夹下
	JSZipUtils.getBinaryContent(templateChose, function(error, content) {
	 if (error) {
	   console.error(error)
	   return
	 }
	 var opts = {}
	 opts.centered = false
	 opts.getImage = function(tagValue) {
	   return new Promise(function(resolve, reject) {
	     JSZipUtils.getBinaryContent(tagValue, function(error, content) {
	       if (error) {
	         return reject(error)
	       }
	       return resolve(content)
	     })
	   })
	 }
	 // 图片有关代码,没有图片的可以删除
	 opts.getSize = function(img, tagValue, tagName) {
	   // return [200, 200] // 图片大小 (固定的)如果你的图片大小要固定,请使用这行代码,将下面return new Promise的那部分注销掉
	   // 非固定(这里是设置宽度最大为300px的图片)
	   let wid = 300
	   return new Promise(function(resolve, reject) {
	     var image = new Image()
	     image.src = tagValue
	     let imgWidth, imgHeight, scale
	     image.onload = function() {
	       imgWidth = image.width
	       imgHeight = image.height
	       scale = 0
	       if (imgWidth > wid) {
	         scale = wid / imgWidth
	         imgWidth = wid
	         imgHeight = imgHeight * scale
	       }
	       resolve([imgWidth, imgHeight])
	     }
	     image.onerror = function(e) {
	       console.log('img, tagName, tagValue : ', img, tagName, tagValue)
	       reject(e)
	     }
	   })
	 }
	 var imageModule = new ImageModule(opts)
	
	 var zip = new PizZip(content)
	 var doc = new Docxtemplater()
	   .loadZip(zip)
	   .setOptions({ linebreaks: true }) // 换行确认,如果你有的文本中有换行符的话,可以选择她导入到word起不起作用
	   .attachModule(imageModule)
	   .compile()
	 doc
	   .resolveData(
	     {
	     	// 这是你导入的数据,这个数据体中的属性或对象一定要和word模板中的插值一样
	       ...report
	     }
	   )
	   .then(function() {
	     console.log('Export...')
	     doc.render()
	     var out = doc.getZip().generate({
	       type: 'blob',
	       mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
	     })
	     // 输出文档,可以自定义自己的文档名
	     saveAs(out, 'Temporary, you need to sync as.docx')
	   })
	})
}

图片word中写法格式 
{#person}
{%docpic}
{/person}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值