DOCX 建立、編輯與分析 是做什麼的?
概述
.docx 檔案本質上是一個包含 XML 檔案的 ZIP 壓縮檔。
快速參考
| 任務 | 方法 |
|---|---|
| 讀取/分析內容 | 使用 markitdown,或解壓縮以存取原始 XML |
| 建立新文件 | 使用 docx-js — 請參閱下方的「建立新文件」章節 |
| 編輯既有文件 | 解壓縮 → 編輯 XML → 重新打包 — 請參閱下方的「編輯既有文件」章節 |
讀取內容
# 文字提取
markitdown document.docx > output.md
# 原始 XML 存取
python scripts/office/unpack.py document.docx unpacked/
接受修訂標記
若要產生一份已接受所有修訂標記的乾淨文件:
python scripts/accept_changes.py input.docx output.docx
建立新文件
使用 JavaScript 產生 .docx 檔案,然後進行驗證。安裝方式:npm install -g docx
設定
const { Document, Packer, Paragraph, TextRun, Table, TableRow, TableCell, ImageRun,
Header, Footer, AlignmentType, PageOrientation, LevelFormat, ExternalHyperlink,
InternalHyperlink, Bookmark, FootnoteReferenceRun, PositionalTab,
PositionalTabAlignment, PositionalTabRelativeTo, PositionalTabLeader,
TabStopType, TabStopPosition, Column, SectionType,
TableOfContents, HeadingLevel, BorderStyle, WidthType, ShadingType,
VerticalAlign, PageNumber, PageBreak } = require('docx');
const doc = new Document({ sections: [{ children: [/* 內容 */] }] });
Packer.toBuffer(doc).then(buffer => fs.writeFileSync("doc.docx", buffer));
驗證
建立檔案後進行驗證。如果驗證失敗,請解壓縮、修正 XML,然後重新打包。
python scripts/office/validate.py doc.docx
頁面大小
// 重要:docx-js 預設為 A4,而非 US Letter
// 為確保一致結果,請務必明確設定頁面大小
sections: [{
properties: {
page: {
size: {
width: 12240, // 8.5 英吋 (DXA 單位)
height: 15840 // 11 英吋 (DXA 單位)
},
margin: { top: 1440, right: 1440, bottom: 1440, left: 1440 } // 1 英吋邊距
}
},
children: [/* 內容 */]
}]
常見頁面尺寸 (DXA 單位,1440 DXA = 1 英吋):
| 紙張 | 寬度 | 高度 | 內容寬度 (1 英吋邊距) |
|---|---|---|---|
| US Letter | 12,240 | 15,840 | 9,360 |
| A4 (預設) | 11,906 | 16,838 | 9,026 |
橫向方向: docx-js 會在內部互換寬度與高度,因此請傳入直向尺寸,讓它處理互換:
size: {
width: 12240, // 傳入短邊作為寬度
height: 15840, // 傳入長邊作為高度
orientation: PageOrientation.LANDSCAPE // docx-js 會在 XML 中互換它們
},
// 內容寬度 = 15840 - 左邊距 - 右邊距 (使用長邊)
樣式 (覆寫內建標題)
使用 Arial 作為預設字型 (通用支援)。為確保可讀性,請將標題保留為黑色。
const doc = new Document({
styles: {
default: { document: { run: { font: "Arial", size: 24 } } }, // 12pt 預設
paragraphStyles: [
// 重要:使用精確的 ID 來覆寫內建樣式
{ id: "Heading1", name: "Heading 1", basedOn: "Normal", next: "Normal", quickFormat: true,
run: { size: 32, bold: true, font: "Arial" },
paragraph: { spacing: { before: 240, after: 240 }, outlineLevel: 0 } }, // TOC 需要 outlineLevel
{ id: "Heading2", name: "Heading 2", basedOn: "Normal", next: "Normal", quickFormat: true,
run: { size: 28, bold: true, font: "Arial" },
paragraph: { spacing: { before: 180, after: 180 }, outlineLevel: 1 } },
]
},
sections: [{
children: [
new Paragraph({ heading: HeadingLevel.HEADING_1, children: [new TextRun("Title")] }),
]
}]
});
清單 (絕對不要使用 Unicode 項目符號)
// ❌ 錯誤 - 切勿手動插入項目符號字元
new Paragraph({ children: [new TextRun("• Item")] }) // 錯誤
new Paragraph({ children: [new TextRun("\u2022 Item")] }) // 錯誤
// ✅ 正確 - 使用包含 LevelFormat.BULLET 的編號設定
const doc = new Document({
numbering: {
config: [
{ reference: "bullets",
levels: [{ level: 0, format: LevelFormat.BULLET, text: "•", alignment: AlignmentType.LEFT,
style: { paragraph: { indent: { left: 720, hanging: 360 } } } }] },
{ reference: "numbers",
levels: [{ level: 0, format: LevelFormat.DECIMAL, text: "%1.", alignment: AlignmentType.LEFT,
style: { paragraph: { indent: { left: 720, hanging: 360 } } } }] },
]
},
sections: [{
children: [
new Paragraph({ numbering: { reference: "bullets", level: 0 },
children: [new TextRun("Bullet item")] }),
new Paragraph({ numbering: { reference: "numbers", level: 0 },
children: [new TextRun("Numbered item")] }),
]
}]
});
// ⚠️ 每個 reference 會建立獨立的編號
// 相同 reference = 繼續 (1,2,3 接著 4,5,6)
// 不同 reference = 重新開始 (1,2,3 接著 1,2,3)
表格
重要:表格需要雙重寬度 - 請同時在表格上設定 columnWidths 以及每個儲存格上的 width。如果未同時設定兩者,表格在某些平台上會顯示不正確。
// 重要:為確保一致呈現,請務必設定表格寬度
// 重要:使用 ShadingType.CLEAR (而非 SOLID) 以防止黑色背景
const border = { style: BorderStyle.SINGLE, size: 1, color: "CCCCCC" };
const borders = { top: border, bottom: border, left: border, right: border };
new Table({
width: { size: 9360, type: WidthType.DXA }, // 永遠使用 DXA (百分比在 Google Docs 中會失效)
columnWidths: [4680, 4680], // 必須加總為表格寬度 (DXA: 1440 = 1 英吋)
rows: [
new TableRow({
children: [
new TableCell({
borders,
width: { size: 4680, type: WidthType.DXA }, // 也需設定在每個儲存格上
shading: { fill: "D5E8F0", type: ShadingType.CLEAR }, // 使用 CLEAR 而非 SOLID
margins: { top: 80, bottom: 80, left: 120, right: 120 }, // 儲存格內距 (內部,不會加到寬度上)
children: [new Paragraph({ children: [new TextRun("Cell")] })]
})
]
})
]
})
表格寬度計算:
永遠使用 WidthType.DXA — WidthType.PERCENTAGE 在 Google Docs 中會失效。
// 表格寬度 = columnWidths 總和 = 內容寬度
// US Letter 搭配 1 英吋邊距: 12240 - 2880 = 9360 DXA
width: { size: 9360, type: WidthType.DXA },
columnWidths: [7000, 2360] // 必須加總為表格寬度
寬度規則:
- 永遠使用
WidthType.DXA— 絕對不要使用WidthType.PERCENTAGE(與 Google Docs 不相容) - 表格寬度必須等於
columnWidths的總和 - 儲存格
width必須符合對應的columnWidth - 儲存格
margins是內部內距;它們會縮減內容區域,但不會增加儲存格寬度 - 對於全寬表格:使用內容寬度 (頁面寬度減去左右邊距)
圖片
// 重要:type 參數為必要
new Paragraph({
children: [new ImageRun({
type: "png", // 必要:png, jpg, jpeg, gif, bmp, svg
data: fs.readFileSync("image.png"),
transformation: { width: 200, height: 150 },
altText: { title: "Title", description: "Desc", name: "Name" } // 三者均為必要
})]
})
分頁符號
// 重要:PageBreak 必須放在 Paragraph 內部
new Paragraph({ children: [new PageBreak()] })
// 或使用 pageBreakBefore
new Paragraph({ pageBreakBefore: true, children: [new TextRun("New page")] })
超連結
// 外部連結
new Paragraph({
children: [new ExternalHyperlink({
children: [new TextRun({ text: "Click here", style: "Hyperlink" })],
link: "https://example.com",
})]
})
// 內部連結 (書籤 + 引用)
// 1. 在目標處建立書籤
new Paragraph({ heading: HeadingLevel.HEADING_1, children: [
new Bookmark({ id: "chapter1", children: [new TextRun("Chapter 1")] }),
]})
// 2. 連結到它
new Paragraph({ children: [new InternalHyperlink({
children: [new TextRun({ text: "See Chapter 1", style: "Hyperlink" })],
anchor: "chapter1",
})]})
註腳
const doc = new Document({
footnotes: {
1: { children: [new Paragraph("Source: Annual Report 2024")] },
2: { children: [new Paragraph("See appendix for methodology")] },
},
sections: [{
children: [new Paragraph({
children: [
new TextRun("Revenue grew 15%"),
new FootnoteReferenceRun(1),
new TextRun(" using adjusted metrics"),
new FootnoteReferenceRun(2),
],
})]
}]
});
定位點
// 在同一行上向右對齊文字 (例如,日期與標題相對)
new Paragraph({
children: [
new TextRun("Company Name"),
new TextRun("\tJanuary 2025"),
],
tabStops: [{ type: TabStopType.RIGHT, position: TabStopPosition.MAX }],
})
// 點線引導 (例如,目錄樣式)
new Paragraph({
children: [
new TextRun("Introduction"),
new TextRun({ children: [
new PositionalTab({
alignment: PositionalTabAlignment.RIGHT,
relativeTo: PositionalTabRelativeTo.MARGIN,
leader: PositionalTabLeader.DOT,
}),
"3",
]}),
],
})
多欄版面配置
// 等寬欄位
sections: [{
properties: {
column: {
count: 2, // 欄位數量
space: 720, // 欄間間距 (DXA: 720 = 0.5 英吋)
equalWidth: true,
separate: true, // 欄間垂直線
},
},
children: [/* 內容會自動跨欄流動 */]
}]
// 自訂寬度欄位 (equalWidth 必須為 false)
sections: [{
properties: {
column: {
equalWidth: false,
children: [
new Column({ width: 5400, space: 720 }),
new Column({ width: 3240 }),
],
},
},
children: [/* 內容 */]
}]
使用 type: SectionType.NEXT_COLUMN 強制分欄。
目錄
// 重要:標題必須僅使用 HeadingLevel - 不允許自訂樣式
new TableOfContents("Table of Contents", { hyperlink: true, headingStyleRange: "1-3" })
頁首/頁尾
sections: [{
properties: {
page: { margin: { top: 1440, right: 1440, bottom: 1440, left: 1440 } } // 1440 = 1 英吋
},
headers: {
default: new Header({ children: [new Paragraph({ children: [new TextRun("Header")] })] })
},
footers: {
default: new Footer({ children: [new Paragraph({
children: [new TextRun("Page "), new TextRun({ children: [PageNumber.CURRENT] })]
})] })
},
children: [/* 內容 */]
}]
docx-js 的重要規則
- 明確設定頁面大小 - docx-js 預設為 A4;美國文件請使用 US Letter (12240 x 15840 DXA)
- 橫向:傳入直向尺寸 - docx-js 會在內部互換寬度/高度;請傳入短邊作為
width,長邊作為height,並設定orientation: PageOrientation.LANDSCAPE - 絕對不要使用
\n- 請使用獨立的 Paragraph 元素 - 絕對不要使用 Unicode 項目符號 - 請使用
LevelFormat.BULLET搭配編號設定 - PageBreak 必須放在 Paragraph 中 - 獨立使用會產生無效的 XML
- ImageRun 需要
type- 請務必指定 png/jpg 等 - 永遠使用 DXA 設定表格
width- 絕對不要使用WidthType.PERCENTAGE(會在 Google Docs 中失效) - 表格需要雙重寬度 -
columnWidths陣列與儲存格width必須同時設定並相符 - 表格寬度 = columnWidths 總和 - 對於 DXA,請確保它們精準加總
- 永遠加入儲存格邊距 - 使用
margins: { top: 80, bottom: 80, left: 120, right: 120 }以獲得可讀的內距 - 使用
ShadingType.CLEAR- 表格陰影絕對不要使用 SOLID - 絕對不要將表格用作分隔線/標尺 - 儲存格有最小高度,會呈現為空白方塊 (包括在頁首/頁尾中);請改用 Paragraph 上的
border: { bottom: { style: BorderStyle.SINGLE, size: 6, color: "2E75B6", space: 1 } }。對於雙欄頁尾,請使用定位點 (參閱定位點章節),而非表格 - TOC 僅需要 HeadingLevel - 標題段落上不允許自訂樣式
- 覆寫內建樣式 - 使用精確 ID:"Heading1"、"Heading2" 等
- 包含
outlineLevel- TOC 需要此設定 (H1 為 0,H2 為 1,依此類推)
編輯既有文件
請依序執行所有 3 個步驟。
步驟 1:解壓縮
python scripts/office/unpack.py document.docx unpacked/
解壓縮 XML、進行美化列印、合併相鄰的文字範圍,並將智慧型引號轉換為 XML 實體 (“ 等),使其在編輯時得以保留。使用 --merge-runs false 可跳過文字範圍合併。
步驟 2:編輯 XML
編輯 unpacked/word/ 中的檔案。請參閱下方的 XML 參考以了解模式。
除非使用者明確要求使用不同名稱,否則請使用 "Claude" 作為作者名稱,用於修訂標記和註解。
請直接使用編輯工具進行字串取代。請勿撰寫 Python 指令碼。 指令碼會引入不必要的複雜性。編輯工具會清楚顯示被取代的內容。
重要:新內容請使用智慧型引號。 當加入包含撇號或引號的文字時,請使用 XML 實體來產生智慧型引號:
<!-- 使用這些實體以獲得專業排版 -->
<w:t>Here’s a quote: “Hello”</w:t>
| 實體 | 字元 |
|---|---|
‘ | ‘ (左單引號) |
’ | ’ (右單引號 / 撇號) |
“ | “ (左雙引號) |
” | ” (右雙引號) |
加入註解: 使用 comment.py 來處理跨多個 XML 檔案的樣板 (文字必須是預先跳脫的 XML):
python scripts/comment.py unpacked/ 0 "Comment text with & and ’"
python scripts/comment.py unpacked/ 1 "Reply text" --parent 0 # 回覆註解 0
python scripts/comment.py unpacked/ 0 "Text" --author "Custom Author" # 自訂作者名稱
然後在 document.xml 中加入標記 (請參閱 XML 參考中的註解章節)。
步驟 3:打包
python scripts/office/pack.py unpacked/ output.docx --original document.docx
使用自動修復功能進行驗證,壓縮 XML,並建立最終的 .docx 檔案。--original 參數會從原始檔案複製設定,以確保相容性。
XML 參考
元素與屬性
| 元素 | 用途 |
|---|---|
<w:p> | 段落 |
<w:r> | 文字範圍 (具有相同格式的文字) |
<w:t> | 文字內容。重要: 使用 xml:space="preserve" 來保留前導/尾隨空格 |
<w:pPr> | 段落屬性 (對齊方式、間距等) |
<w:rPr> | 文字範圍屬性 (字型、大小、粗體等) |
<w:body> | 文件主體 |
<w:sectPr> | 章節屬性 (頁面大小、邊距、頁首/頁尾) |
<w:tr> | 表格列 |
<w:tc> | 表格儲存格 |
<w:tbl> | 表格 |
<w:hyperlink> | 超連結 |
<w:bookmarkStart> / <w:bookmarkEnd> | 書籤標記 |
<w:commentRangeStart> / <w:commentRangeEnd> | 註解範圍標記 |
<w:rPr> 中的 <w:rStyle> | 套用字元樣式 (例如 w:val="Hyperlink") |
常見操作
變更字型:
<w:rPr>
<w:rFonts w:ascii="Arial" w:hAnsi="Arial"/>
</w:rPr>
變更段落對齊方式:
<w:pPr>
<w:jc w:val="center"/>
</w:pPr>
加入粗體:
將 <w:b/> 加入 <w:rPr>。
變更文字顏色:
將 <w:color w:val="2E75B6"/> 加入 <w:rPr>。
設定頁面邊距:
在 <w:sectPr> 中找到 <w:pgMar>:
<w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="720" w:footer="720" w:gutter="0"/>
新增段落:
<w:p>
<w:pPr>
<w:spacing w:before="120" w:after="120"/>
</w:pPr>
<w:r>
<w:rPr>
<w:rFonts w:ascii="Arial" w:hAnsi="Arial"/>
<w:sz w:val="24"/>
</w:rPr>
<w:t xml:space="preserve">您的文字內容</w:t>
</w:r>
</w:p>
常見陷阱
- 空格: 文字範圍 (
<w:r>) 之間的換行和縮排會產生空格。請盡可能將文字範圍保持在同一行。 - 段落屬性順序: 某些 Java 實作 (尤其是 Apache POI) 在嵌套區塊中對順序很敏感。請在
<w:pPr>中保持邏輯順序。 - 段落之間的軟性換行: 使用
<w:br/>(在<w:r>內部) 來表示段落內的換行。 - 重複的樣式定義: 如果文件包含自訂樣式,重新定義它們會造成重複。請在編輯前檢查
styles.xml。