文章目录

  • 一、docxtemplater
    • 1.引入相关的库
    • 2.替换数据格式
    • 3.根据模板填充word文档
  • 二、officegen
    • 1.引入相关的库
    • 2.生成word
    • 3.自定义样式
      • 3.1 重写水平线
  • 三、adm-zip
    • 1.引入相关的库
    • 2.解压缩(解析word为原始数据)
    • 3.根据模板填充文件数据(word/document.xml)
    • 4.压缩(导出word)

一、docxtemplater

用途:使用 Javascript 从应用程序内部生成 docx、pptx 或 xlsx

注意:安装3.5版本即可。不用安装最新版本(官方声明:open-docxtemplater-image-module版本在docxtemplater3.5.2之前是兼容的),可能存在docx无法替换图片 Cannot read properties of undefined (reading ‘part’)的问题。

1.引入相关的库

搭配pizzip(或jszip)、open-docxtemplater-image-module使用

  • pizzip:一个同步压缩文件的库,是JsZip的一个分支

  • open-docxtemplater-image-module:开源 docxtemplater 图片模块

// 引入相关的库
const PizZip = require('pizzip')
const Docxtemplater = require('docxtemplater')
const ImageModule = require('open-docxtemplater-image-module') // 读取模板文件

2.替换数据格式

//文本替换模板
{name1}--------------obj.name1
{name2}--------------obj.name2//图片替换模板
{%image}--------------obj.image

3.根据模板填充word文档

/*** 填充word文档* @param {string} inputPath 模板文件* @param {{}} data 替换数据* @param {string} outPutPath 输出文件*/
fileHelper.replaceWord = async function (inputPath, data, outPutPath) {try {console.log(inputPath, outPutPath)// 读取文件,以二进制文件形式保存const content = fs.readFileSync(inputPath, 'binary', function () {})// 压缩数据const zip = new PizZip(content)// 生成模板文档const doc = new Docxtemplater()const opts = {centered: false,getImage: function (tagValue, tagName) {return fs.readFileSync(path.join(__dirname, '../template/图片/' + tagValue))},getSize: function (img, tagValue, tagName) {return [250, 200]}}doc.attachModule(new ImageModule(opts)).loadZip(zip).setData(data)// 渲染数据生成文档doc.render()// 将文档转换文nodejs能使用的bufconst buf = doc.getZip().generate({ type: 'nodebuffer' })// 输出文件await fs.writeFile(outPutPath, buf, function () {})} catch (error) {console.log(error)}
}

二、officegen

用途:为 Microsoft Office 2007 及更高版本创建 Office Open XML 文件(Word、Excel 和 Powerpoint),无需外部工具,只需纯 Javascript。 officegen应该适用于任何支持 Node.js 的环境,包括 Linux、OSX 和 Windows。 officegen还支持带有嵌入数据的PowerPoint原生图表对象。

1.引入相关的库

const officegen = require('officegen')

2.生成word

async function generateWord (date, inputPath, outputPath) {
const docx = officegen('docx')// 1.添加文本const title1 = docx.createP({ align: 'center' })title1.addText('文本一', { blod: true, font_face: '宋体', font_size: 12 })title1.addLineBreak() // 换行title1.addText('文本二')// 2.添加表格let pObjTable = docx.createP()const table = [['col1', 'col2', 'col3'],[1, 'All grown-ups were once children', '']]const tableStyle = {tableColWidth: 3261,tableSize: 24,tableAlign: 'center',tableVAlign: 'center',borders: true, // default is false. if true, default border size is 4borderSize: 2, // To use this option, the 'borders' must set as true, default is 4columns: [{ width: 1261 }, { width: 1000 }, { width: 1000 }] // Table logical columns}   pObjTable = docx.createTable(table, tableStyle)// 3.添加图片const pObjPic = docx.createP()pObjPic.addImage('image.png')// 获取文件名const fileName = 'result.docx'// 导出wordconst out = fs.createWriteStream(path.resolve(outputPath, fileName))// 文件写入out.on('error', function (err) {// console.log(err)return err})const result = docx.generate(out) // 服务端生成worddocx.on('finalize', function (written) {// console.log(//   'Finish to create Word file.\nTotal bytes created: ' + written + '\n'// )return result})return result
}

3.自定义样式

3.1 重写水平线

  else if (objs_list[i].data[j].horizontal_line) {console.log(objs_list[i].data[j])var height =typeof objs_list[i].data[j].options.height == 'string'? objs_list[i].data[j].options.height: '.75'var fillcolor =typeof objs_list[i].data[j].options.fillcolor == 'string'? objs_list[i].data[j].options.fillcolor: 'e0e0e0'//outString += `<w:r><w:pict><v:rect o:spt="1" style="width:0;height:${height}pt" o:hralign="center" o:hrstd="t" o:hr="t" fillcolor="#${fillcolor}" stroked="f"></v:rect></w:pict></w:r>`;outString += `<w:r><w:pict><v:rect o:spt="1" style="height:${height}pt;width:0pt;" fillcolor="#${fillcolor}" filled="t" stroked="f" coordsize="21600,21600" o:hr="t" o:hrstd="t" o:hrnoshade="t" o:hralign="center"></v:rect></w:pict></w:r>`// Bookmark start support:}

/*** Insert a horizontal line inside this paragraph.*/
MakeDocxP.prototype.addHorizontalLine = function (opt) {var newP = this// newP.data[newP.data.length] = { horizontal_line: true }newP.data[newP.data.length] = { horizontal_line: true, options: opt || {} }
}


使用:

 // 4.添加水平线const pObj = docx.createP()pObj.addHorizontalLine({height: '2',fillcolor: 'FF0000'})

三、adm-zip

用途:

  • 将 zip 文件直接解压缩到磁盘或内存缓冲区中
  • 压缩文件并将它们以 .zip 格式或压缩缓冲区存储到磁盘
  • 从现有 .zip 更新/添加新/删除文件的内容

说明:可以将word当作zip文件进行解压缩,编辑其中内容

注意:无法解析doc文件,只能解析docx文件。

(docx格式与doc格式都是word文本格式,但是二者的差距实际上是很大的,docx和doc的区别显著的一点就是体积大小的不同。docx格式就是一个zip文件,我们可以拿winrar打开docx文件,得到一堆的文件,很类似android程序或者win7桌面窗体的源码,你在里面可以找到各种配置文件,文本文件和媒体文件。)

1.引入相关的库

const AdmZip = require('adm-zip')

2.解压缩(解析word为原始数据)

 const zip = new AdmZip('../test.docx') // 将该docx解压到指定文件夹temp下,word/document.xml为word文件数据zip.extractAllTo('../temp', /* overwrite */ true)

3.根据模板填充文件数据(word/document.xml)

 const result = await fs.promises.readFile(fileName)let str = result.toString() //正则表达式替换数据const data=[{sourceRegx:/\$\{CE_day\}/g,targetStr:'test'}]data.forEach(item => {str = str.replace(item.sourceRegx, item.targetStr)})await fs.promises.writeFile(fileName, str.toString())

4.压缩(导出word)

try {const zip = new AdmZip() zip.addLocalFolder(inputPath)//inputPath:word文件夹路径await zip.writeZip(outputPath)//result.docx} catch (error) {console.log('生成word,err:', error)}

nodejs-编辑、生成word(docxtemplater、officegen、adm-zip)相关推荐

  1. springboot中使用freemarker生成word文档并打包成zip下载(简历)

    一.设计出的简历模板图以及给的简历小图标切图         二.按照简历模板图新建简历word文件 :${字段名},同时将图片插入到word中,并将建好的word文件另存为xml文件:    三.直 ...

  2. 使用word模板生成word文档的各类方案

    使用word模板生成word文档的各类方案 生成word的各种方案 word另存xml进行后续处理 2003版本word(.doc)的xml处理并生成word 2007版本word(.docx)的xm ...

  3. SpringCloud之利用FTL生成Word报表并下载

    1.首先,新建一个word文档:里面写需要下载的东西 2.编辑完后,另存为xml格式(不用管xml里面是什么),然后将后缀名xml改为ftl 3.这个ftl就是在Java代码中可生成word的模板文件 ...

  4. java导出生成word

    最近做的项目,需要将一些信息导出到word中.在网上找了好多解决方案,现在将这几天的总结分享一下. 目前来看,java导出word大致有6种解决方案: 1:Jacob是Java-COM Bridge的 ...

  5. Java生成Word文档

    在开发文档系统或办公系统的过程中,有时候我们需要导出word文档.在网上发现了一个用PageOffice生成word文件的功能,就将这块拿出来和大家分享. 生成word文件与我们编辑word文档本质上 ...

  6. java导出生成word(类似简历导出)

    最近做的项目,需要将一些信息导出到word中.在网上找了好多解决方案,现在将这几天的总结分享一下. 目前来看,java导出word大致有6种解决方案: 1:Jacob是Java-COM Bridge的 ...

  7. java 中导出word后压缩文件_Java批量导出word压缩后的zip文件案例

    一.js代码,由于参数比较大所以利用form表单使用post导出 function export_word(){ var selectedRows = $("#dg").datag ...

  8. python自动生成word报告_python自动化生成分析报告,让你的工作效率提升10倍+

    打开搜狗搜索APP,查看更多精彩资讯 如果你每天都需要输出分析报告,报告模式基本一致,只是更换里面的分析数据,每天重复着同样的工作,费时费力,工作能力没有丝毫的提升,但是如果你学过python,你就可 ...

  9. 使用PHPWord生成word文档

    有时我们需要把网页内容保存为Word文档格式,以供其他人员查看和编辑.PHPWord是一个用纯PHP编写的库,使用PHPWord可以轻松处理word文档内容,生成你想要的word文档. 下载源码 安装 ...

最新文章

  1. cocoaPods安装、更新第三方库
  2. 【SSH网上商城项目实战17】购物车基本功能的实现
  3. stateflow中向量与矩阵
  4. Java-代理模式的理解
  5. AtCoder Beginner Contest 192 F - Potion 背包dp
  6. 【渝粤教育】国家开放大学2018年秋季 0505-22T护理学基础 参考试题
  7. 简单明了 - Git 使用超详细教程
  8. CPU上跑到 33 FPS 的简单轻量级人体姿态估计网络
  9. 0xc000007b——应用程序无法正常启动解决办法
  10. python的功能及特点_使用Python这么多年,才发现Python还有这些实用的功能和特点...
  11. 酷派5890刷recovery详细教程
  12. html怎样制作动态页面,HTML如何制作网页动态时钟
  13. CMD如何直接运行文件
  14. 射频信号处理知识点点滴滴
  15. Python Web开发技巧III
  16. java类与对象实验报告心得体会_java实习实训报告心得【三篇】
  17. 【算法思路】常见岛屿数量的算法题
  18. 记录一下uni-app开发中遇到的坑
  19. C#第十二章 项目案例:QQ数据库管理
  20. 我眼中的光明·第一周

热门文章

  1. blockly 代码html,【blockly入门指引】2, 在网页中使用blockly
  2. 关于NLP中的文本预处理的完整教程
  3. charles抓取微信小程序数据(抓取http和https数据)
  4. 执古之道,以御今之有
  5. 第4天 java高级特性增强 ---有用 第一遍
  6. 笔记本安装Win10+Ubuntu16.04 LTS 双系统
  7. 入门软件测试--兼容性(iOS)
  8. spark shuff
  9. ASUS华硕笔记本电脑枪神6Plus超竞版ROG Strix G733CW 3070Ti原装出厂Win11系统恢复原厂oem系统
  10. 外国人眼中中的外伤性白内障简介