NodeJS生成Word文件
简介
利用 officegen 插件 来实现
https://www.npmjs.com/package/officegen
示例代码
模块文章中的示例代码,可生成 example.docx 文件
const officegen = require('officegen')
const fs = require('fs')
// 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.'
)
})
// Create a new paragraph:
let pObj = docx.createP()
pObj.addText('Simple')
pObj.addText(' with color', { color: '000088' })
pObj.addText(' and back color.', { color: '00ffff', back: '000088' })
pObj = docx.createP()
pObj.addText('Since ')
pObj.addText('officegen 0.2.12', {
back: '00ffff',
shdType: 'pct12',
shdColor: 'ff0000'
}) // Use pattern in the background.
pObj.addText(' you can do ')
pObj.addText('more cool ', { highlight: true }) // Highlight!
pObj.addText('stuff!', { highlight: 'darkGreen' }) // Different highlight color.
pObj = docx.createP()
pObj.addText('Even add ')
pObj.addText('external link', { link: 'https://github.com' })
pObj.addText('!')
pObj = docx.createP()
pObj.addText('Bold + underline', { bold: true, underline: true })
pObj = docx.createP({ align: 'center' })
pObj.addText('Center this text', {
border: 'dotted',
borderSize: 12,
borderColor: '88CCFF'
})
pObj = docx.createP()
pObj.options.align = 'right'
pObj.addText('Align this text to the right.')
pObj = docx.createP()
pObj.addText('Those two lines are in the same paragraph,')
pObj.addLineBreak()
pObj.addText('but they are separated by a line break.')
docx.putPageBreak()
pObj = docx.createP()
pObj.addText('Fonts face only.', { font_face: 'Arial' })
pObj.addText(' Fonts face and size.', { font_face: 'Arial', font_size: 40 })
docx.putPageBreak()
pObj = docx.createP()
// We can even add images:
// pObj.addImage('some-image.png')
// Let's generate the Word document into a file:
let out = fs.createWriteStream('example.docx')
out.on('error', function(err) {
console.log(err)
})
// Async call to generate the output file:
docx.generate(out)
体会
- 代码编写非常快速
- 能够设置word文字的样式、大小等
分类:
JavaScript
标签:
文档处理
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)