officegen可以用来生成pptx、docx、xlsx格式的文件,可以非常具体地对文件进行操作,比如addText、addImage等等,非常实用,npm地址是这个

下面是一个示例代码,亲测很好用。

不过我这次项目使用了另一个库叫html-to-docx,因为我要进行转换的时候,内容里面带有html标签,我希望转换后的docx文件,可以保留这些格式,但是officegen解决不了这个问题,html-to-docx就很完美地解决了。

const officegen = require('officegen')
const fs = require('fs')
const doc = require('./test.json')

// Create an empty Word object:
let docx = officegen('docx')

// Officegen calling this function after finishing to generate the docx document:
docx.on('finalize', function (written) {
  console.log('Finish to create a Microsoft Word document.')
})

// Officegen calling this function to report errors:
docx.on('error', function (err) {
  console.log(err)
})

// 文档标题
let pObj = docx.createP()
pObj.addText(doc.doc_title, {
  bold: true,
  font_size: 18,
})

let out = fs.createWriteStream('example.docx')

out.on('error', function (err) {
  console.log(err)
})

// Async call to generate the output file:
docx.generate(out)
最后编辑:2024年05月18日 ©著作权归作者所有

发表评论