LOGO OA教程 ERP教程 模切知识交流 PMS教程 CRM教程 开发文档 其他文档  
 
网站管理员

docxjs如何快速生成word文档?

admin
2025年6月23日 12:48 本文热度 79


docxjs是一款较为强大的docx格式文档处理的js库,基本可以处理我们遇到的所有有关于docx的文档问题。支持内置方式的word生成、解析、格式渲染。除此之外,我们还可以通过自定义方式直接通过xml方式渲染word包括但不限于字体样式、字体大小、段落样式、间距、颜色等一系列我们可能遇到的问题。


01

安装和使用

安装

$npm install --save docx // 或者 $yarn add docx -D


简单使用

import * as fs from "fs";import { Document, Packer, Paragraph, TextRun } from "docx";
// 文档由章节数组[sections]组成  // 这里示例只是创建了一个章节const doc = new Document({    sections: [        {            properties: {},            children: [                new Paragraph({                    children: [                        new TextRun("Hello World"),                        new TextRun({                            text: "Foo Bar",                            bold: true,                        }),                        new TextRun({                            text: "\tGithub is the best",                            bold: true,                        }),                    ],                }),            ],        },    ],});
// Used to export the file into a .docx filePacker.toBuffer(doc).then((buffer) => {    fs.writeFileSync("My Document.docx", buffer);});
// Done! My Document.docx文件就创建好了


02

封装模块


01

Document

Document是docxjs中封装word文档的顶级对象,是最后生成.docx的最终


封装类。您可以将所有的Paragraphs 添加到Document中,注意,一个.docx文档只有一个Document对象。


常用的配置属性如下:

  • creator
  • description
  • title
  • subject
  • keywords
  • lastModifiedBy
  • revision
  • externalStyles
  • styles
  • numbering
  • footnotes
  • hyperlinks
  • background


如何使用配置项?

我们可以看下通过修改配置项实现改变document背景色的示例来了解下:

const doc = new docx.Document({    background: {        color: "C45911",    },});
02

Sections

每一个文档都是由多一个或者多个Sections构成的。一个Section是一组具有一组特定属性的Paragraphs ,这些属性用于定义将出现文本的页面。属性包括页面大小、页码、页面方向、页眉、边框和边距。例如,您可以有一个带有页眉和页脚的纵向部分,另一个没有页脚的横向部分,以及一个显示当前页码的页眉。

const doc =newDocument({    sections:[{        children:[            newParagraph({                children:[newTextRun("Hello World")],            }),        ],    }];});

Section Type

设置节类型决定了节的内容相对于前一节的放置方式。例如,有五种不同的类型:
  • CONTINUOUS
  • EVEN_PAGE
  • NEXT_COLUMN
  • NEXT_PAGE
  • ODD_PAGE
const doc = new Document({    sections: [{        properties: {            type: SectionType.CONTINUOUS,        }        children: [            new Paragraph({                children: [new TextRun("Hello World")],            }),        ],    }];});
03

Paragraph

docx文件中OpenXML 中的所有内容(文本、图像、图表等)都按段落组织。Paragraphs 需要对Sections的理解。


构造创建

我们可以在创建paragraph对象时通过构造器直接初始化创建。

import { Paragraph } from "docx";const paragraph = new Paragraph("Short hand Hello World");

子集嵌套创建

如果Paragraph中有多个子集,比如我一个段落里面既包含Text文本也有Image图片、Table之类元素的话,我们可以将它直接放在Paragraph的children属性里,children属性可传入一个数组对象。

const paragraph = new Paragraph({    children: [                        new TextRun("Lorem Ipsum Foo Bar"),                         new TextRun("Hello World"),                        new SymbolRun("F071")    ],});

Text单元素创建

如果Paragraph只有纯文本信息的话,我可以通过Paragraph的text属性进行创建。

const paragraph = new Paragraph({    text: "Short hand notation for adding text.",});


创建完paragraph对象后记得将其添加到对应的sections中:

const doc = new Document({    sections: [{        children: [paragraph],    }];});


基本属性

属性类型
强制的?可能的值
textstring可选的
headingHeadingLevel可选的HEADING_1
HEADING_2
HEADING_3
HEADING_4
HEADING_5
HEADING_6,
TITLE
borderIBorderOptions可选的top
bottom
left
right.
其中每一个都是属性对象都是
 IBorderPropertyOptions 类型。单击此处查看示例
spacingISpacingProperties可选的请参阅下面的 ISpacingProperties
outlineLevelnumber可选的
alignmentAlignmentType可选的
headingHeadingLevel可选的
bidirectionalboolean可选的
thematicBreakboolean可选的
pageBreakBeforeboolean可选的
contextualSpacingboolean可选的
indentIIndentAttributesProperties可选的
keepLinesboolean可选的
keepNextboolean可选的
children(TextRun or ImageRun or Hyperlink)[]可选的
stylestring可选的
tabStop{ left?: ITabStopOptions; right?: ITabStopOptions; maxRight?: { leader: LeaderType; }; center?: ITabStopOptions }可选的
bullet{ level: number }可选的
numbering{ num: ConcreteNumbering; level: number; custom?: boolean }可选的
widowControlboolean可选的
frameIFrameOptions可选的


 IBorderPropertyOptions属性配置


Paragraph的边框设置可以给boder设置topbottomleftright 四个属性对象,对象类型为IBorderPropertyOptions。


属性类型
备注
colorstring必须
spacenumber必须
stylestring必须
sizenumber必须


ISpacingProperties


属性
类型
备注可能的值
afternumber可选

beforenumber可选

linenumber可选

lineRuleLineRuleType可选
AT_LEAST
EXACTLY
AUTO


配置示例

// 配置使用const paragraph =new Paragraph({  text:"Hello World.",  // text文本  heading: HeadingLevel.HEADING_1, // 标题  border: {    top: {        color: "auto",        space: 1,        style: "single",        size: 6,    },    bottom: {        color: "auto",        space: 1,        style: "single",        size: 6,    },  },  // 边框配置  shading: {    type: ShadingType.REVERSE_DIAGONAL_STRIPE,    color: "00FFFF",    fill: "FF0000",  }, // 阴影配置  widowControl: true, // 允许第一行/最后一行显示在单独的页面上  spacing: {          before: 200  },      // 边距配置,主要是配置段落格式的,如段前、段后、固定字高等  outlineLevel: 0, // 配置word文档的段落大纲类型  });

该文章在 2025/6/23 12:48:29 编辑过
关键字查询
相关文章
正在查询...
点晴ERP是一款针对中小制造业的专业生产管理软件系统,系统成熟度和易用性得到了国内大量中小企业的青睐。
点晴PMS码头管理系统主要针对港口码头集装箱与散货日常运作、调度、堆场、车队、财务费用、相关报表等业务管理,结合码头的业务特点,围绕调度、堆场作业而开发的。集技术的先进性、管理的有效性于一体,是物流码头及其他港口类企业的高效ERP管理信息系统。
点晴WMS仓储管理系统提供了货物产品管理,销售管理,采购管理,仓储管理,仓库管理,保质期管理,货位管理,库位管理,生产管理,WMS管理系统,标签打印,条形码,二维码管理,批号管理软件。
点晴免费OA是一款软件和通用服务都免费,不限功能、不限时间、不限用户的免费OA协同办公管理系统。
Copyright 2010-2025 ClickSun All Rights Reserved