docx 库 Document 对象完全指南:从零创建 Word 文档与全部配置项详解
2026/9/17 1:20:39 网站建设 项目流程

docx 库 Document 对象完全指南:从零创建 Word 文档与全部配置项详解

【免费下载链接】docxEasily generate and modify .docx files with JS/TS with a nice declarative API. Works for Node and on the Browser.项目地址: https://gitcode.com/GitHub_Trending/do/docx

导读

Document是 docx 库中一切 .docx 文件的起点:它代表 Word 文档本身,所有内容(段落、表格、页眉页脚等)都被组织进它的sections中,最后再通过Packer导出为真实文件。本篇以 docs/usage/document.md 为核心,结合仓库源码(src/file/file.ts、src/file/core-properties/properties.ts、src/file/settings/settings.ts 等)与示例(demo/54-custom-properties.ts、demo/60-track-revisions.ts),完整覆盖文档创建、元数据属性、背景色、自定义属性、特性开关与兼容性配置,读完即可用一行行配置生成带完整元数据与兼容选项的专业 Word 文档。

创建你的第一个 Document

Document对象是 .docx 之旅的起点,它就是你最终生成的 Word 文档本体。所有内容——无论是Paragraph(段落)、Table(表格)还是目录——都必须放进sections数组中:

const doc = new docx.Document({ sections: [ { children: [new Paragraph("Hello World")], }, ], });

在仓库中,这个对外导出的Document类实际上对应 src/file/file.ts 中的File类(@publicApi,注释明确写有 "The File class (exported asDocument) is the main entry point for creating DOCX documents")。构造时它会完成一整条装配流水线:

  1. 用传入的creatorrevisionlastModifiedBy等生成核心属性(core properties);
  2. 初始化numberingcommentscustomPropertiesfootnotesendnotessettingsstylesmedia等所有文档部件;
  3. word/document.xmldocProps/core.xmldocProps/app.xmldocProps/custom.xmlstyles.xmlnumbering.xmlfootnotes.xmlendnotes.xmlsettings.xmlcomments.xml建立默认 relationship(见addDefaultRelationships,src/file/file.ts);
  4. 逐个addSection,把每个 section 的children追加到document.xml的 body 中。

而真正渲染w:document根元素的是 src/file/document/document.ts,它会写入几十个 XML 命名空间声明(wpcmcrmww14w15等,见 src/file/document/document-attributes.ts),因此生成的文件无需任何额外声明即可被 Word 正确解析。Document.add()方法还可以直接追加段落、表格、目录等块级元素并支持链式调用。

Document Properties:文档元数据

你可以为 Word 文档添加元数据属性,它们会显示在 Word 的「文件 > 信息」面板以及文件属性中:

const doc = new docx.Document({ creator: "Dolan Miu", description: "My extremely interesting document", title: "My Document", subject: "Report", keywords: "report, annual, finance", sections: [ /* ... */ ], });

Metadata Properties(元数据属性)

PropertyTypeDescription
titlestringDocument title
subjectstringDocument subject
creatorstringAuthor name
keywordsstringKeywords for searching
descriptionstringDocument description/comments
lastModifiedBystringLast person to modify
revisionnumberRevision number

从源码看,这些属性由 src/file/core-properties/properties.ts 中的CoreProperties类写出,会生成标准的cp:corePropertiesXML 块:

  • title<dc:title>subject<dc:subject>creator<dc:creator>(Dublin Core 命名空间);
  • keywords<cp:keywords>description<dc:description>lastModifiedBy<cp:lastModifiedBy>
  • revision<cp:revision>
  • 无论是否传参,都会自动追加<dcterms:created><dcterms:modified>两个时间戳元素,类型为xsi:type="dcterms:W3CDTF"(W3C 日期时间格式),值为当前时间。

另外在 src/file/file.ts 中可以看到三个默认值兜底逻辑:creator未提供时默认"Un-named"lastModifiedBy默认"Un-named"revision默认1。也就是说即使你不写元数据,生成的文件也始终携带合法的核心属性部件。

Options by Category:按类别速查全部配置

Document的完整选项定义在 src/file/core-properties/properties.ts 的IPropertiesOptions类型中,与文档表格完全对应。以下是按功能类别整理的配置项。

Content Options(内容选项)

PropertyTypeDescription
sectionsISectionOptions[]Document sections
commentsICommentsOptionsDocument comments
footnotesRecord<string, { children: Paragraph[] }>Footnotes

ISectionOptions的完整定义见 src/file/file.ts:每个 section 可包含headersdefault/first/even三种)、footers(同样三种)、properties(页面大小、边距、方向等节属性)以及必填的children内容数组。此外IPropertiesOptions还支持endnotes(尾注,Record<string, { children: Paragraph[] }>结构,与 footnotes 一致),相关实现见 src/file/endnotes/endnotes.ts。

Styling Options(样式选项)

PropertyTypeDescription
stylesIStylesOptionsCustom styles
externalStylesstringExternal XML styles
numberingINumberingOptionsNumbering definitions
fontsFontOptions[]Embedded fonts
defaultTabStopnumberDefault tab stop (twips)

从源码看(src/file/file.ts),样式装配有三条路径:传了externalStyles时,会用ExternalStylesFactory解析外部 XML 样式并与默认样式合并;只传styles时用DefaultStylesFactory生成并合并自定义样式;两者都没传时生成全默认样式。fonts则由FontWrapper(src/file/fonts/font-wrapper.ts)负责把字体嵌入文档。defaultTabStop会被写进settings.xml<w:defaultTabStop>(单位为 twips,1 英寸 = 1440 twips)。

Document Behavior(文档行为)

PropertyTypeDescription
backgroundIDocumentBackgroundOptionsDocument background
features{ trackRevisions?: boolean; updateFields?: boolean }Feature flags
evenAndOddHeaderAndFootersbooleanDifferent odd/even headers
hyphenationIHyphenationOptionsHyphenation settings

evenAndOddHeaderAndFooters会在settings.xml中写入<w:evenAndOddHeaders>,配合 section 里的headers.even/footers.even使用可实现奇偶页不同的页眉页脚(详见 docs/usage/headers-and-footers.md)。hyphenation支持autoHyphenation(自动断词)、hyphenationZone(断词区,twips)、consecutiveHyphenLimit(连续断词行数上限)、doNotHyphenateCaps(全大写不参与断词)四个子项,对应w:autoHyphenationw:hyphenationZonew:consecutiveHyphenLimitw:doNotHyphenateCaps元素(见 src/file/settings/settings.ts)。

Compatibility(兼容性)

PropertyTypeDescription
compatibilityICompatibilityOptionsCompatibility settings
compatabilityModeVersionnumberWord version compatibility

注意:compatabilityModeVersion(注意拼写)在源码中被标记为 deprecated(见 src/file/settings/settings.ts),建议改用compatibility.version。两者的关系是:compatibility.version ?? compatabilityModeVersion ?? 15,即都不传时默认取15

Full list of options(完整选项列表)

PropertyTypeNotes
sectionsISectionOptions[]Optional
titlestringOptional
subjectstringOptional
creatorstringOptional
keywordsstringOptional
descriptionstringOptional
lastModifiedBystringOptional
revisionnumberOptional
externalStylesstringOptional
stylesIStylesOptionsOptional
numberingINumberingOptionsOptional
commentsICommentsOptionsOptional
footnotesRecord<string, { children: Paragraph[] }>Optional
backgroundIDocumentBackgroundOptionsOptional
features{ trackRevisions?: boolean; updateFields?: boolean; }Optional
compatabilityModeVersionnumberOptional
compatibilityICompatibilityOptionsOptional
customPropertiesICustomPropertyOptions[]Optional
evenAndOddHeaderAndFootersbooleanOptional
defaultTabStopnumberOptional
fontsFontOptions[]Optional
hyphenationIHyphenationOptionsOptional

这些选项可以随意自由组合,也可以一个都不传(除sections外全部可选)。

修改文档背景色

给文档设置十六进制背景色非常简单:

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

从源码看(src/file/document/document-background/document-background.ts),IDocumentBackgroundOptions除了color(十六进制字符串,无需#前缀,会经hexColorValue校验),还支持themeColor(如"accent1""dark1"等主题色枚举)、themeShade(加深主题色)和themeTint(减淡主题色,后两者为十六进制数值)。最终渲染为document.xml中的<w:background w:color="C45911"/>元素,并且Settings会自动附带<w:displayBackgroundShape/>(src/file/settings/settings.ts),确保 Word 能显示背景形状。

Custom Properties:自定义属性

除了标准元数据,还可以添加自定义属性,它们同样会出现在 Word 的文档属性面板中:

const doc = new docx.Document({ customProperties: [ { name: "Department", value: "Engineering", }, { name: "Project Code", value: "PRJ-2024-001", }, { name: "Approved", value: true, }, { name: "Version", value: 2.5, }, ], sections: [ /* ... */ ], });

自定义属性支持以下值类型:

  • string- Text values(文本)
  • number- Numeric values(数值,布尔与数字会在写入时转换为字符串)
  • boolean- True/false values(布尔)

仓库中的完整示例见 demo/54-custom-properties.ts,它同时设置了标准属性(creator、title、subject、description)和SubtitleAddress两个自定义属性,然后通过Packer.toBuffer(doc)写出My Document.docx

从源码看(src/file/custom-properties/custom-properties.ts),自定义属性被渲染到独立的docProps/custom.xml部件中,每个<property>元素带有:

  • 固定formatId{D5CDD505-2E9C-101B-9397-08002B2CF9AE}(OOXML 自定义属性标准 GUID);
  • 自增pid从 2 开始(源码注释说明这是 Office 规范约定);
  • name:属性名;
  • 值统一写为<vt:lpwstr>(variant type 的 "long pointer to wide string")。

也就是说,自定义属性的本质是以Properties为根、vt:类型命名空间承载的键值对集合,Word 与 docProps 工具链都能读取。

Document Features:特性开关

features用来启用特殊行为,例如修订跟踪(Track Changes)与字段自动更新:

const doc = new docx.Document({ features: { trackRevisions: true, // Enable track changes updateFields: true, // Update fields (like TOC) when opened }, sections: [ /* ... */ ], });

使用目录(Table of Contents)时建议设置updateFields: true,这样文档打开时会自动刷新目录页码。

从源码看(src/file/file.ts),这两个开关最终写入settings.xml

  • trackRevisions: true<w:trackRevisions/>。demo 示例 demo/60-track-revisions.ts 注释明确指出:该设置让 Word 在文档生成之后跟踪用户新做的修订;而文档中已有的插入/删除文本(InsertedTextRunDeletedTextRun)无论是否开启此开关都会保留显示;
  • updateFields: true<w:updateFields/>,指示打开文档时重新计算域(TOC、页码等)。

对应实现在 src/file/settings/settings.ts。更完整的修订功能(插入、删除、批注回复等)可参考 docs/usage/change-tracking.md。

定位单位:twips、EMU 与换算

API 中涉及定位的参数都基于 OOXML 规范的「1/20 点」(twips,即 twentieths of a point)为单位。常见换算关系:

  • 1 英寸 = 72 点 = 1440 twips = 914400 EMU;
  • 1 点 = 20 twips;
  • 1 厘米 ≈ 567 twips(1 厘米 ≈ 28.35 点);
  • EMU(English Metric Unit)用于图片尺寸等更精细的定位,1 英寸 = 914400 EMU。

defaultTabStophyphenationZone等参数即以此为单位;而Document级的背景色则不受此单位体系影响(使用十六进制颜色值)。仓库 src/util/values.ts 中定义了UniversalMeasurePositiveUniversalMeasurePercentage等带单位类型(如"10.5mm""-5pt""50%"),供边距、缩进、行距等测量值使用。

Compatibility:兼容性设置详解

兼容性设置是可选配置,用于保持早期文字处理软件创建文档的视觉保真度。其中一部分设置提供特定行为(如下详述),另一部分则是让应用程序模拟既有文字处理软件(如 WordPerfect、Word 6.x/95/97)的行为:

const doc = new docx.Document({ compatibility: { version: 15, doNotExpandShiftReturn: true, }, });

Compatibility Options(兼容性选项表)

以下全部选项都映射到settings.xml<w:compat>元素下(实现见 src/file/settings/compatibility.ts):

PropertyTypeNotesPossible Values
versionnumberOptional15,16,17
useSingleBorderforContiguousCellsbooleanOptionaltrue,false,undefined
wordPerfectJustificationbooleanOptionaltrue,false,undefined
noTabStopForHangingIndentbooleanOptionaltrue,false,undefined
noLeadingbooleanOptionaltrue,false,undefined
spaceForUnderlinebooleanOptionaltrue,false,undefined
noColumnBalancebooleanOptionaltrue,false,undefined
balanceSingleByteDoubleByteWidthbooleanOptionaltrue,false,undefined
noExtraLineSpacingbooleanOptionaltrue,false,undefined
doNotLeaveBackslashAlonebooleanOptionaltrue,false,undefined
underlineTrailingSpacesbooleanOptionaltrue,false,undefined
doNotExpandShiftReturnbooleanOptionaltrue,false,undefined
spacingInWholePointsbooleanOptionaltrue,false,undefined
lineWrapLikeWord6booleanOptionaltrue,false,undefined
printBodyTextBeforeHeaderbooleanOptionaltrue,false,undefined
printColorsBlackbooleanOptionaltrue,false,undefined
spaceWidthbooleanOptionaltrue,false,undefined
showBreaksInFramesbooleanOptionaltrue,false,undefined
subFontBySizebooleanOptionaltrue,false,undefined
suppressBottomSpacingbooleanOptionaltrue,false,undefined
suppressTopSpacingbooleanOptionaltrue,false,undefined
suppressSpacingAtTopOfPagebooleanOptionaltrue,false,undefined
suppressTopSpacingWPbooleanOptionaltrue,false,undefined
suppressSpBfAfterPgBrkbooleanOptionaltrue,false,undefined
swapBordersFacingPagesbooleanOptionaltrue,false,undefined
convertMailMergeEscbooleanOptionaltrue,false,undefined
truncateFontHeightsLikeWP6booleanOptionaltrue,false,undefined
macWordSmallCapsbooleanOptionaltrue,false,undefined
usePrinterMetricsbooleanOptionaltrue,false,undefined
doNotSuppressParagraphBordersbooleanOptionaltrue,false,undefined
wrapTrailSpacesbooleanOptionaltrue,false,undefined
footnoteLayoutLikeWW8booleanOptionaltrue,false,undefined
shapeLayoutLikeWW8booleanOptionaltrue,false,undefined
alignTablesRowByRowbooleanOptionaltrue,false,undefined
forgetLastTabAlignmentbooleanOptionaltrue,false,undefined
adjustLineHeightInTablebooleanOptionaltrue,false,undefined
autoSpaceLikeWord95booleanOptionaltrue,false,undefined
noSpaceRaiseLowerbooleanOptionaltrue,false,undefined
doNotUseHTMLParagraphAutoSpacingbooleanOptionaltrue,false,undefined
layoutRawTableWidthbooleanOptionaltrue,false,undefined
layoutTableRowsApartbooleanOptionaltrue,false,undefined
useWord97LineBreakRulesbooleanOptionaltrue,false,undefined
doNotBreakWrappedTablesbooleanOptionaltrue,false,undefined
doNotSnapToGridInCellbooleanOptionaltrue,false,undefined
selectFieldWithFirstOrLastCharacterbooleanOptionaltrue,false,undefined
applyBreakingRulesbooleanOptionaltrue,false,undefined
doNotWrapTextWithPunctuationbooleanOptionaltrue,false,undefined
doNotUseEastAsianBreakRulesbooleanOptionaltrue,false,undefined
useWord2002TableStyleRulesbooleanOptionaltrue,false,undefined
growAutofitbooleanOptionaltrue,false,undefined
useFELayoutbooleanOptionaltrue,false,undefined
useNormalStyleForListbooleanOptionaltrue,false,undefined
doNotUseIndentAsNumberingTabStopbooleanOptionaltrue,false,undefined
useAlternateEastAsianLineBreakRulesbooleanOptionaltrue,false,undefined
allowSpaceOfSameStyleInTablebooleanOptionaltrue,false,undefined
doNotSuppressIndentationbooleanOptionaltrue,false,undefined
doNotAutofitConstrainedTablesbooleanOptionaltrue,false,undefined
autofitToFirstFixedWidthCellbooleanOptionaltrue,false,undefined
underlineTabInNumberingListbooleanOptionaltrue,false,undefined
displayHangulFixedWidthbooleanOptionaltrue,false,undefined
splitPgBreakAndParaMarkbooleanOptionaltrue,false,undefined
doNotVerticallyAlignCellWithSpbooleanOptionaltrue,false,undefined
doNotBreakConstrainedForcedTablebooleanOptionaltrue,false,undefined
ignoreVerticalAlignmentInTextboxesbooleanOptionaltrue,false,undefined
useAnsiKerningPairsbooleanOptionaltrue,false,undefined
cachedColumnBalancebooleanOptionaltrue,false,undefined

常用兼容项的行为说明

  • version:设置 Word 兼容模式版本,15对应 Word 2013,16对应 Word 2016/2019,17对应 Word 2021。源码中通过createCompatibilitySetting(src/file/settings/compatibility-setting/compatibility-setting.ts)写出<w:compatSetting w:name="compatibilityMode" w:uri="http://schemas.microsoft.com/office/word" w:val="15"/>,并默认取15
  • useSingleBorderforContiguousCells:表格连续单元格冲突时使用简化边框规则(w:useSingleBorderforContiguousCells);
  • doNotExpandShiftReturn:不以软换行(Shift+Enter)结尾的行不做两端对齐(w:doNotExpandShiftReturn);
  • suppressSpBfAfterPgBrk:分页符后的首行不使用段前间距(w:suppressSpBfAfterPgBrk);
  • doNotSnapToGridInCell:表格单元格内含对象时不吸附文档网格(w:doNotSnapToGridInCell);
  • useAnsiKerningPairs:使用字体的 ANSI 字距对(w:useAnsiKerningPairs)。

组合实战:一个完整的 Document

将以上所有能力组合起来,可得到一个带元数据、自定义属性、背景色、特性开关与兼容模式的完整文档:

import * as fs from "fs"; import { Document, Packer, Paragraph } from "docx"; const doc = new Document({ creator: "Report Bot", lastModifiedBy: "Report Bot", title: "2024 年度财务报告", subject: "Finance", keywords: "report, annual, finance", description: "Auto-generated annual financial report", revision: 3, background: { color: "FFFFFF", }, customProperties: [ { name: "Department", value: "Finance" }, { name: "Approved", value: true }, { name: "Version", value: 2.5 }, ], features: { trackRevisions: false, updateFields: true, // 让 TOC 打开时自动刷新 }, compatibility: { version: 16, doNotExpandShiftReturn: true, useSingleBorderforContiguousCells: true, }, sections: [ { properties: { page: { margin: { top: 720, bottom: 720, left: 720, right: 720 }, // twips }, }, children: [new Paragraph("Hello World")], }, ], }); Packer.toBuffer(doc).then((buffer) => { fs.writeFileSync("My Document.docx", buffer); });

运行后,右键文件查看属性即可看到标题、作者、关键词、自定义属性与修订号;用 Word 打开则可见背景、兼容模式与字段自动更新均已生效。仓库 demo 目录(demo/)还提供了50-readme-demo.ts54-custom-properties.ts60-track-revisions.ts1-basic.ts等多个可运行示例,以及浏览器端演示 demo/browser-demo.html(库同时支持 Node 与浏览器环境)。

进一步阅读

  • 节与页面布局:docs/usage/sections.md、docs/usage/page-layout.md
  • 样式体系:docs/usage/styling-with-js.md、docs/usage/styling-with-xml.md
  • 页眉页脚:docs/usage/headers-and-footers.md
  • 修订跟踪与批注:docs/usage/change-tracking.md、docs/usage/comments.md
  • 导出打包:docs/usage/packers.md
  • 快速上手:docs/quickstart.md

【免费下载链接】docxEasily generate and modify .docx files with JS/TS with a nice declarative API. Works for Node and on the Browser.项目地址: https://gitcode.com/GitHub_Trending/do/docx

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询