关于node通过officegen生成word使用(服务端)

1、首先安装officegen

  cnpm install officegen --save

2、在controller层引入

  const officegen = require('officegen')

  const fs = require('fs')

3、在functron里使用officegen

  <--定义写入文档的数据和字体样式-->

  //定义文档的标题

  let tObj = docx.createP({ align: 'center' });    //居中

 

   tObj.addText(title, { bold: true, font_face: 'Arial', font_size: 18 });   // 标题样式  

 

   tObj.addLineBreak()     //换行

  //定义内容

  let pObj = docx.createP()

  pObj.addText('办案进展:', {  font_size: 14, font_face: '方正仿宋简体' })

       pObj.addText(list.title, {  font_size: 14, font_face: '方正仿宋简体' })

       pObj.addLineBreak()

  //如果写入的是列表,直接循环就好

  //生成文档,存放文档的路径要先创建好

  let out = await fs.createWriteStream(`public/process//文档.docx`)

      out.on('error', function (err) {

        console.log(err + '111111111111111')

    })

    docx.generate(out)

4、将创建好的文档返回给前端即可

  ctx.body = {     
    status: 1,
        url: `/process/文档.docx`
      }
 
 5、整体代码  
const officegen = require('officegen')
const fs = require('fs')


getProcessListWord: async (ctx, next) => {
    //省略获取数据步骤
    let docx = officegen('docx')

    docx.on('finalize', function (written) {
      console.log(
        'Finish to create a Microsoft Word document.'
      )
    })

    docx.on('error', function (err) {
      console.log(err)
    })
    
    //写入world文档

    const title = caseInfo.client_name + caseInfo.cause
    let tObj = docx.createP({ align: 'center' });
    tObj.addText(title, { bold: true, font_face: 'Arial', font_size: 18 });
    tObj.addLineBreak()
    tObj.addLineBreak()
    let pObj = docx.createP()
    for (let i = 0; i < list.length; i++) {
      pObj.addText('字段名称:', {  font_size: 14, font_face: '方正仿宋简体' })
      pObj.addText(list[i].title, {  font_size: 14, font_face: '方正仿宋简体' })

    }

    const now = UTIL.moment(Date.now()).format('YYYY-MM-DD_HH_mm_ss');   //定义一个时间
    await File.mkdir(`public/process`);
    // Async call to generate the output file:
    let out = await fs.createWriteStream(`public/process/文档_${now}.docx`)

    out.on('error', function (err) {
      console.log(err + '111111111111111')
    })
    docx.generate(out)
    ctx.body = {
      status: 1,
      url: `/process/文档_${now}.docx`
    }

  },
        
    

 

 

 

  

 

 

 

  

  

 

 

posted on 2021-09-03 11:09  尘不修仙  阅读(1269)  评论(0编辑  收藏  举报

导航