vue3+docxtemplater生成word文件

一、简介

docxtemplater是一个从 docx/pptx 模板生成 docx/pptx 文档的库,使用 JSON作为数据输入处理 docx 和 pptx 模板,可以使用条件、循环在文档中插入表格、html以及图像等任何内容。其中html及图像模块收费,可以用docxtemplater-image-module-free代替图像模块。

二、需要安装的依赖

1、npm i docxtemplater

2、npm i docxtemplater-image-module-free

3、npm i pizzip

4、npm i file-saver(如果使用的是ts还需安装类型声明文件,npm i @types/file-saver)

三、页面引用

import docxtemplater from 'docxtemplater'

import PizZip from 'pizzip'

import PizZipUtils from 'pizzip/utils'

import { saveAs } from 'file-saver'

import ImageModule from 'docxtemplater-image-module-free'

四、制作Word模板

根据需要导出的word文件的要求,先使用word制作出模板,数据使用{变量}代替。

(1)标签类型

a、简单文本

在模板中输入:

Hello {name} !

并给出以下数据(data.json):

{
    name:'John'
}

docxtemplater 将产生 (output.docx):

Hello John !

b、条件判断

条件标签以#开始,/结束,在模板中输入以下内容:

{#hasKitty}Cat’s name: {kitty}{/hasKitty}
{#hasDog}Dog’s name: {dog}{/hasDog}

并给出以下数据:

{
    "first_name":"Jane",
    "hasKitty": true,
    "kitty": "Minie"
    "hasDog": false,
    "dog": null
}

当hasKitty为true时,才去渲染其中的内容。文档中将呈现以下内容:

Cat’s name: Minie

c、循环输出

循环同样以#开始,/结束,在模板中输入以下内容:

{#products}
    {name}, {price} €
{/products}

并给出以下数据:

{
    "products": [
        { name: "Windows", price: 100 },
        { name: "Mac OSX", price: 200 },
        { name: "Ubuntu", price: 0 }
    ]
}

文档呈现内容:

Windows, 100 €
Mac OSX, 200 €
Ubuntu, 0€

(2)图片类型

给出以下数据:

{
    "imgs": [
        { url: "xxx/xxx.jpg" },
        { url: "xxx/xxx.jpg" }
    ]
}

模板内写法:{#imgs}{%url}{/imgs}

文档便会在模板对应占位符的位置循环展现两张图片

(3)模板示例

制作完成后请将模板文件放到项目文件夹的public下。

 五、js/ts实现代码

   //导出word文件(docData为处理好的数据)
      wordExport(docData: any) {
        // word导出 - 编译
        const loadFile = function loadFile(url: any, callback: any) {
          PizZipUtils.getBinaryContent(url, callback)
        }
        loadFile('/report.docx', function (error: any, content: any) {
          if (error) {
            throw error
          }
          // 有图片的话,需加上下面这段代码
          let opts: any = {}
          opts.centered = false
          opts.fileType = 'docx'
          opts.getImage = function (tagValue: any) {
            return new Promise(function (resolve, reject) {
              PizZipUtils.getBinaryContent(tagValue, function (error: any, content: any) {
                if (error) {
                  return reject(error)
                }
                return resolve(content)
              })
            })
          }
          opts.getSize = function () {
            return [255, 195]//这里是生成的word文件里图片的宽和高
          }
          let imageModule = new ImageModule(opts)
          var zip = new PizZip(content)
          let doc = new docxtemplater().loadZip(zip).attachModule(imageModule).compile()
          // 有图片的话,需加载图片处理模块
          doc.resolveData(docData).then(function () {
            console.log('ready')
            doc.render() //apply them (replace all occurences of {first_name} by Hipp, ...)
            var out = doc.getZip().generate({
              type: 'blob',
              mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
            }) //Output the document using Data-URI
            saveAs(out, '测试文件' + '.docx')
          })
        })
      }

六、参考的文档及文章

https://docxtemplater.readthedocs.io/en/latest/index.html

https://www.jianshu.com/p/0de31429b12a

https://www.jianshu.com/p/b3622d6f8d98

  • 1
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值