mcpField
D
docx

docx

github.com/makerjackieドキュメント048 回インストール36 週間前に更新
リポジトリ

docx について

docxは、DOCX文書の作成、読み取り、編集、検証を支援するスキルです。docx-jsとXMLの展開・編集・再パッケージ化を使い、変更履歴、表、画像、レイアウトの手順も扱います。

主な機能

  1. 01DOCXのテキスト抽出とXML確認
  2. 02docx-jsによる文書作成
  3. 03文書の展開・編集・再パッケージ化
  4. 04変更履歴とコメントの処理
  5. 05PDFやページ画像への変換
  6. 06文書の検証と一般的な問題の修正

活用シーン

  1. 01変更履歴付きDOCXからテキストを抽出
  2. 02新しいDOCXファイルの作成と検証
  3. 03既存文書のXML内容を編集
  4. 04変更履歴の承認や文書コメントの追加

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/makerjackie/jackie-skills-everyday --skill docx

インストール後、Claude Code で/docxを入力して読み込まれたか確認します。

詳細

(中国語)DOCX の作成、編集、分析

概要

.docx ファイルは、XML ファイルを含む ZIP アーカイブです。

クイックリファレンス

タスク方法
内容の読み取り・分析pandoc を使うか、展開して生の XML を確認
新しいドキュメントの作成docx-js を使用します。以下の「新しいドキュメントの作成」を参照してください
既存ドキュメントの編集展開 → XML を編集 → 再圧縮します。以下の「既存ドキュメントの編集」を参照してください
.doc を .docx に変換する

古い形式の .doc ファイルは、編集前に変換する必要があります。

python scripts/office/soffice.py --headless --convert-to docx document.doc
内容の読み取り
# Text extraction with tracked changes
pandoc --track-changes=all document.docx -o output.md

# Raw XML access
python scripts/office/unpack.py document.docx unpacked/
画像への変換
python scripts/office/soffice.py --headless --convert-to pdf document.docx
pdftoppm -jpeg -r 150 document.pdf page
変更履歴を承認する

変更履歴をすべて承認したクリーンなドキュメントを作成するには、次のようにします(LibreOffice が必要です)。

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,
        TableOfContents, HeadingLevel, BorderStyle, WidthType, ShadingType,
        VerticalAlign, PageNumber, PageBreak } = require('docx');

const doc = new Document({ sections: [{ children: [/* content */] }] });
Packer.toBuffer(doc).then(buffer => fs.writeFileSync("doc.docx", buffer));
検証

ファイルを作成したら、検証してください。検証に失敗した場合は、展開して XML を修正し、再圧縮します。

python scripts/office/validate.py doc.docx
ページサイズ
// CRITICAL: docx-js defaults to A4, not US Letter
// Always set page size explicitly for consistent results
sections: [{
  properties: {
    page: {
      size: {
        width: 12240,   // 8.5 inches in DXA
        height: 15840   // 11 inches in DXA
      },
      margin: { top: 1440, right: 1440, bottom: 1440, left: 1440 } // 1 inch margins
    }
  },
  children: [/* content */]
}]

一般的な用紙サイズ(DXA 単位、1440 DXA = 1 インチ):

用紙幅高さコンテンツ幅(余白 1 インチ)
US レター12,24015,8409,360
A4(デフォルト)11,90616,8389,026

横向き: docx-js は内部で幅と高さを入れ替えるため、縦向きの寸法を渡し、入れ替えは docx-js に任せます。

size: {
  width: 12240,   // Pass SHORT edge as width
  height: 15840,  // Pass LONG edge as height
  orientation: PageOrientation.LANDSCAPE  // docx-js swaps them in the XML
},
// Content width = 15840 - left margin - right margin (uses the long edge)
スタイル(組み込みの見出しスタイルを上書きする)

デフォルトフォントには、広くサポートされている Arial を使用します。読みやすさを保つため、タイトルは黒にします。

const doc = new Document({
  styles: {
    default: { document: { run: { font: "Arial", size: 24 } } }, // 12pt default
    paragraphStyles: [
      // IMPORTANT: Use exact IDs to override built-in styles
      { 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 } }, // outlineLevel required for TOC
      { 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 の箇条書き記号は絶対に使用しない)
// ❌ WRONG - never manually insert bullet characters
new Paragraph({ children: [new TextRun("• Item")] })  // BAD
new Paragraph({ children: [new TextRun("\u2022 Item")] })  // BAD

// ✅ CORRECT - use numbering config with 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")] }),
    ]
  }]
});

// ⚠️ Each reference creates INDEPENDENT numbering
// Same reference = continues (1,2,3 then 4,5,6)
// Different reference = restarts (1,2,3 then 1,2,3)
表

重要:表には二重の幅指定が必要です — 表の columnWidths と各セルの width の両方を設定してください。両方を設定しないと、一部のプラットフォームで表が正しく表示されません。

// CRITICAL: Always set table width for consistent rendering
// CRITICAL: Use ShadingType.CLEAR (not SOLID) to prevent black backgrounds
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 }, // Always use DXA (percentages break in Google Docs)
  columnWidths: [4680, 4680], // Must sum to table width (DXA: 1440 = 1 inch)
  rows: [
    new TableRow({
      children: [
        new TableCell({
          borders,
          width: { size: 4680, type: WidthType.DXA }, // Also set on each cell
          shading: { fill: "D5E8F0", type: ShadingType.CLEAR }, // CLEAR not SOLID
          margins: { top: 80, bottom: 80, left: 120, right: 120 }, // Cell padding (internal, not added to width)
          children: [new Paragraph({ children: [new TextRun("Cell")] })]
        })
      ]
    })
  ]
})

表の幅の計算:

常に WidthType.DXA を使用してください。WidthType.PERCENTAGE は Google Docs で正しく動作しません。

// Table width = sum of columnWidths = content width
// US Letter with 1" margins: 12240 - 2880 = 9360 DXA
width: { size: 9360, type: WidthType.DXA },
columnWidths: [7000, 2360]  // Must sum to table width

幅のルール:

  • 常に WidthType.DXA を使用してください — WidthType.PERCENTAGE は使用しないでください(Google Docs と互換性がありません)
  • 表の幅は columnWidths の合計と一致する必要があります
  • セルの width は対応する columnWidth と一致させてください
  • セルの margins は内側の余白です。セルの幅に加算されるのではなく、コンテンツ領域を狭めます
  • 全幅の表では、コンテンツ幅(ページ幅から左右の余白を差し引いた幅)を使用します
画像
// CRITICAL: type parameter is REQUIRED
new Paragraph({
  children: [new ImageRun({
    type: "png", // Required: png, jpg, jpeg, gif, bmp, svg
    data: fs.readFileSync("image.png"),
    transformation: { width: 200, height: 150 },
    altText: { title: "Title", description: "Desc", name: "Name" } // All three required
  })]
})
改ページ
// CRITICAL: PageBreak must be inside a Paragraph
new Paragraph({ children: [new PageBreak()] })

// Or use pageBreakBefore
new Paragraph({ pageBreakBefore: true, children: [new TextRun("New page")] })
目次
// CRITICAL: Headings must use HeadingLevel ONLY - no custom styles
new TableOfContents("Table of Contents", { hyperlink: true, headingStyleRange: "1-3" })
ヘッダー/フッター
sections: [{
  properties: {
    page: { margin: { top: 1440, right: 1440, bottom: 1440, left: 1440 } } // 1440 = 1 inch
  },
  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: [/* content */]
}]
docx-js の重要なルール
  • ページサイズを明示的に設定する — docx-js のデフォルトは A4 です。米国向けのドキュメントでは US レター(12240 x 15840 DXA)を使用してください
  • 横向きでは縦向きの寸法を渡す — docx-js は内部で幅と高さを入れ替えます。短辺を width、長辺を height として渡し、orientation: PageOrientation.LANDSCAPE を設定してください
  • \n は絶対に使用しない — 独立した Paragraph 要素を使用してください
  • Unicode の箇条書き記号は絶対に使用しない — 番号設定で LevelFormat.BULLET を使用してください
  • PageBreak は Paragraph の中に配置する — 単独で配置すると無効な XML が生成されます
  • ImageRun には type が必要 — 必ず png/jpg などを指定してください
  • 表の width は常に DXA で設定する — WidthType.PERCENTAGE は使用しないでください(Google Docs で正しく動作しません)
  • 表には二重の幅指定が必要 — columnWidths 配列とセルの width の両方を設定し、値を一致させてください
  • 表の幅は columnWidths の合計にする — DXA では、合計が正確に一致するようにしてください
  • セルの余白を必ず追加する — 読みやすい余白には margins: { top: 80, bottom: 80, left: 120, right: 120 } を使用してください
  • ShadingType.CLEAR を使用する — 表の網掛けには SOLID を使用しないでください
  • 目次では HeadingLevel のみを使用する — 見出し段落にカスタムスタイルを適用しないでください
  • 組み込みスタイルを上書きする — 「Heading1」、「Heading2」などの正確な ID を使用してください
  • outlineLevel を含める — 目次に必要です(H1 は 0、H2 は 1 など)

既存ドキュメントの編集

次の 3 つの手順を順番どおりに実行してください。

手順 1:展開
python scripts/office/unpack.py document.docx unpacked/

XML を抽出して整形し、隣接する run を結合します。また、スマート引用符を XML エンティティ(“ など)に変換して、編集後も保持されるようにします。run の結合を省略するには、--merge-runs false を使用してください。

ステップ 2:XML を編集する

unpacked/word/ 内のファイルを編集します。パターンについては、以下の XML リファレンスを参照してください。

変更履歴とコメントの作成者には、ユーザーが別の名前を明示的に指定しない限り、「Claude」を使用してください。

文字列の置換には Edit ツールを直接使用してください。Python スクリプトは作成しないでください。スクリプトは不要な複雑さを招きます。Edit ツールを使うと、置換対象が明確に表示されます。

重要:新しい内容にはスマートクォートを使用してください。 アポストロフィや引用符を含むテキストを追加する場合は、XML エンティティを使用してスマートクォートを出力してください。


<w:t>Here&#x2019;s a quote: &#x201C;Hello&#x201D;</w:t>
エンティティ文字
&#x2018;‘(左シングル引用符)
&#x2019;’(右シングル引用符/アポストロフィ)
&#x201C;“(左ダブル引用符)
&#x201D;”(右ダブル引用符)

コメントの追加: 複数の XML ファイルにまたがる定型処理には comment.py を使用してください(テキストは事前に XML エスケープしておく必要があります)。

python scripts/comment.py unpacked/ 0 "Comment text with &amp; and &#x2019;"
python scripts/comment.py unpacked/ 1 "Reply text" --parent 0  # reply to comment 0
python scripts/comment.py unpacked/ 0 "Text" --author "Custom Author"  # custom author name

次に、document.xml にマーカーを追加してください(「XML リファレンス」の「コメント」を参照)。

ステップ 3:パッケージ化する
python scripts/office/pack.py unpacked/ output.docx --original document.docx

自動修復による検証と XML の圧縮を行い、DOCX を作成します。検証をスキップするには --validate false を使用してください。

自動修復で修正される項目:

  • durableId が 0x7FFFFFFF 以上の場合(有効な ID を再生成します)
  • 空白を含む <w:t> に xml:space="preserve" がない場合

自動修復で修正されない項目:

  • XML の形式不正、要素の入れ子の不正、リレーションシップの不足、スキーマ違反
よくある落とし穴
  • <w:r> 要素全体を置き換える: 変更履歴を追加する場合は、<w:r>...</w:r> ブロック全体を置き換え、<w:del>...<w:ins>... を兄弟要素として配置します。変更履歴タグを run の内部に挿入しないでください。
  • <w:rPr> の書式を保持する: 太字やフォントサイズなどを維持するため、元の run の <w:rPr> ブロックを変更履歴の run にコピーしてください。

XML リファレンス

スキーマへの準拠
  • <w:pPr> 内の要素の順序: <w:pStyle>、<w:numPr>、<w:spacing>、<w:ind>、<w:jc>、最後に <w:rPr>
  • 空白: 先頭または末尾に空白がある <w:t> には xml:space="preserve" を追加します
  • RSID: 8 桁の 16 進数である必要があります(例:00AB1234)
変更履歴

挿入:

<w:ins w:id="1" w:author="Claude" w:date="2025-01-01T00:00:00Z">
  <w:r><w:t>inserted text</w:t></w:r>
</w:ins>

削除:

<w:del w:id="2" w:author="Claude" w:date="2025-01-01T00:00:00Z">
  <w:r><w:delText>deleted text</w:delText></w:r>
</w:del>

<w:del> 内: <w:t> の代わりに <w:delText> を、<w:instrText> の代わりに <w:delInstrText> を使用してください。

最小限の編集 — 変更箇所だけをマークします:


<w:r><w:t>The term is </w:t></w:r>
<w:del w:id="1" w:author="Claude" w:date="...">
  <w:r><w:delText>30</w:delText></w:r>
</w:del>
<w:ins w:id="2" w:author="Claude" w:date="...">
  <w:r><w:t>60</w:t></w:r>
</w:ins>
<w:r><w:t> days.</w:t></w:r>

段落/リスト項目全体の削除 — 段落の内容をすべて削除する場合は、段落記号も削除としてマークし、次の段落と結合されるようにします。<w:pPr><w:rPr> 内に <w:del/> を追加してください:

<w:p>
  <w:pPr>
    <w:numPr>...</w:numPr>  
    <w:rPr>
      <w:del w:id="1" w:author="Claude" w:date="2025-01-01T00:00:00Z"/>
    </w:rPr>
  </w:pPr>
  <w:del w:id="2" w:author="Claude" w:date="2025-01-01T00:00:00Z">
    <w:r><w:delText>Entire paragraph content being deleted...</w:delText></w:r>
  </w:del>
</w:p>

<w:pPr><w:rPr> 内に <w:del/> がないと、変更を承諾したときに空の段落/リスト項目が残ります。

別の作成者による挿入を取り消す場合 — その作成者の挿入の内側に削除をネストします:

<w:ins w:author="Jane" w:id="5">
  <w:del w:author="Claude" w:id="10">
    <w:r><w:delText>their inserted text</w:delText></w:r>
  </w:del>
</w:ins>

別の作成者による削除を復元する場合 — その作成者の削除は変更せず、その後に挿入を追加します:

<w:del w:author="Jane" w:id="5">
  <w:r><w:delText>deleted text</w:delText></w:r>
</w:del>
<w:ins w:author="Claude" w:id="10">
  <w:r><w:t>deleted text</w:t></w:r>
</w:ins>
コメント

comment.py を実行した後(ステップ 2 を参照)、document.xml にマーカーを追加します。返信では --parent フラグを使用し、親のマーカー内にネストしてください。

重要:<w:commentRangeStart> と <w:commentRangeEnd> は <w:r> の兄弟要素であり、<w:r> の内側に配置してはいけません。


<w:commentRangeStart w:id="0"/>
<w:del w:id="1" w:author="Claude" w:date="2025-01-01T00:00:00Z">
  <w:r><w:delText>deleted</w:delText></w:r>
</w:del>
<w:r><w:t> more text</w:t></w:r>
<w:commentRangeEnd w:id="0"/>
<w:r><w:rPr><w:rStyle w:val="CommentReference"/></w:rPr><w:commentReference w:id="0"/></w:r>


<w:commentRangeStart w:id="0"/>
  <w:commentRangeStart w:id="1"/>
  <w:r><w:t>text</w:t></w:r>
  <w:commentRangeEnd w:id="1"/>
<w:commentRangeEnd w:id="0"/>
<w:r><w:rPr><w:rStyle w:val="CommentReference"/></w:rPr><w:commentReference w:id="0"/></w:r>
<w:r><w:rPr><w:rStyle w:val="CommentReference"/></w:rPr><w:commentReference w:id="1"/></w:r>
画像
  1. 画像ファイルを word/media/ に追加します
  2. word/_rels/document.xml.rels にリレーションシップを追加します:
<Relationship Id="rId5" Type=".../image" Target="media/image1.png"/>
  1. [Content_Types].xml にコンテンツタイプを追加します:
<Default Extension="png" ContentType="image/png"/>
  1. document.xml で参照します:
<w:drawing>
  <wp:inline>
    <wp:extent cx="914400" cy="914400"/>  
    <a:graphic>
      <a:graphicData uri=".../picture">
        <pic:pic>
          <pic:blipFill><a:blip r:embed="rId5"/></pic:blipFill>
        </pic:pic>
      </a:graphicData>
    </a:graphic>
  </wp:inline>
</w:drawing>

依存関係

  • pandoc:テキストの抽出
  • docx:npm install -g docx(新しいドキュメント)
  • LibreOffice:PDF 変換(サンドボックス環境向けに scripts/office/soffice.py で自動設定されます)
  • Poppler:画像出力用の pdftoppm

コメント