微信小程序云开发将数据库数据生成word文件

演示如何通过云函数把数据存入word模板中,源代码见cloudfunctions/genarateDocument/index.js,整个过程分为以下几个过程:(1) 创建云函数,并安装doctemplater、pizzip;(2) 读取数据库集合中的所有数据;(3) 通过doctemplater把数据写入word;(4) 把生成的word文件上传到云存储,供微信小程序端下载浏览。

云函数genarateDocument/index.js完整源代码如下:

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

// 云函数入口文件

const cloud = require('wx-server-sdk')

cloud.init()

var PizZip = require('pizzip');

var Docxtemplater = require('docxtemplater');

var fs = require('fs');

var path = require('path');

 

// 云函数入口函数

exports.main = async(event, context) => {

  var content = fs.readFileSync(path.resolve(__dirname, 'template.docx'), 'binary');

  var zip = new PizZip(content);

  var doc;

  try {

    doc = new Docxtemplater(zip);

  } catch (error) {

    // Catch compilation errors (errors caused by the compilation of the template : misplaced tags)

    errorHandler(error);

  }

 

  //set the templateVariables

  doc.setData({

    teamName: 'John',

    matchItem: 'Doe',

  });

 

  try {

    // render the document (replace all occurences of {first_name} by John, {last_name} by Doe, ...)

    doc.render()

  } catch (error) {

    // Catch rendering errors (errors relating to the rendering of the template : angularParser throws an error)

    //errorHandler(error);

  }

 

  var buffer = doc.getZip()

    .generate({

      type: 'nodebuffer'

    });

 

    return  await  cloud.uploadFile({

    cloudPath: "doc.docx",

    fileContent: buffer, //excel二进制文件

  })

}

转载自:https://item.jd.com/13038316.html

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值