\ お問い合わせはこちら /

Python で Word を自動操作する ― win32com 完全ガイド

Windows環境でWordがインストールされている方向けの記事です。

win32com を活用すれば、Word 文書(.docx / .doc / .rtf)を生成・編集・検索置換・表作成・画像挿入・PDF変換までフルに自動化できます。

本記事では、その方法をご紹介します。

1. 事前準備(pywin32 インストール)

pywin32 のインストール

Python
pip install pywin32

Word を起動する基本コード

Python
from win32com.client import Dispatch, constants

word = Dispatch("Word.Application")
word.Visible = True

Word を終了

Python
word.Quit()

2. Word.Application・Documents 操作

文書を新規作成

Python
doc = word.Documents.Add()
doc.Content.Text = "Hello from Python!"

既存文書を開く

Python
doc = word.Documents.Open(r"C:\path\to\doc.docx")

上書き保存 / 別名保存

Python
doc.Save()  # 上書き

doc.SaveAs(r"C:\path\to\new.docx")  # 別名保存

PDF として保存

Python
wdFormatPDF = 17
doc.SaveAs(r"C:\path\to\out.pdf", FileFormat=wdFormatPDF)

文書を閉じる

Python
doc.Close(SaveChanges=False)

3. Range / Selection の基本操作

文書全体のテキスト取得・書き込み

Python
text = doc.Content.Text
doc.Content.Text = "上書き内容"

文末に追記する

Python
end = doc.Content.End
doc.Range(end, end).InsertAfter("\n追記しました")

文頭に挿入

Python
doc.Range(0, 0).InsertBefore("=== 先頭に追記 ===\n")

書式設定(太字・色・サイズ)

Python
rng = doc.Range(0, 10)
rng.Font.Bold = True
rng.Font.Color = 255
rng.Font.Size = 16

4. 検索・置換(Find / Replace)

単純置換(文書全体)

Python
find = doc.Content.Find
find.Text = "旧社名"
find.Replacement.Text = "新社名"
find.Execute(Replace=constants.wdReplaceAll)

ワイルドカード(正規表現風)の利用

Python
find = doc.Content.Find
find.Text = "[0-9]{4}/[0-9]{2}/[0-9]{2}"
find.MatchWildcards = True
find.Replacement.Text = "****/**/**"
find.Execute(Replace=constants.wdReplaceAll)

5. 段落操作

段落を列挙する

Python
for p in doc.Paragraphs:
    print(p.Range.Text)

段落の書式設定

Python
p = doc.Paragraphs(1)
p.Alignment = constants.wdAlignParagraphCenter
p.Range.Font.Bold = True
p.Range.Font.Size = 14

改行を挿入

Python
doc.Range().InsertParagraphAfter()

6. 箇条書き・番号リスト

箇条書きにする

Python
p = doc.Paragraphs.Add()
p.Range.Text = "箇条書き項目"
p.Range.ListFormat.ApplyBulletDefault()

番号付きリストにする

Python
p = doc.Paragraphs.Add()
p.Range.Text = "番号リスト項目"
p.Range.ListFormat.ApplyNumberDefault()

7. 表(Table)操作

表を作成する

Python
table = doc.Tables.Add(
    Range=doc.Range(0, 0),
    NumRows=3,
    NumColumns=3
)

セルへ値を設定

Python
table.Cell(1, 1).Range.Text = "商品名"
table.Cell(1, 2).Range.Text = "数量"
table.Cell(1, 3).Range.Text = "金額"

行・列を追加

Python
table.Rows.Add()
table.Columns.Add()

ヘッダー行の書式設定

Python
header = table.Rows(1)
header.Range.Font.Bold = True
header.Shading.BackgroundPatternColor = 12632256

8. 画像・図形の挿入

画像を挿入

Python
inline = doc.Range(0, 0).InlineShapes.AddPicture(
    FileName=r"C:\path\image.png",
    LinkToFile=False,
    SaveWithDocument=True
)
inline.Width = 300
inline.Height = 200

図形(シェイプ)を追加

Python
shape = doc.Shapes.AddShape(
    Type=1,
    Left=50,
    Top=50,
    Width=200,
    Height=100
)
shape.TextFrame.TextRange.Text = "図形のテキスト"

9. ヘッダー・フッター操作

ヘッダーを編集する

Python
section = doc.Sections(1)
header = section.Headers(constants.wdHeaderFooterPrimary)
header.Range.Text = "会社名:Python自動化株式会社"

フッター(ページ番号)

Python
footer = section.Footers(constants.wdHeaderFooterPrimary)
footer.Range.Text = "Page "
footer.PageNumbers.Add(constants.wdAlignParagraphRight)

10. スタイル操作

見出しスタイルを適用

Python
doc.Range(0, 10).Style = "見出し 1"

カスタムスタイルの作成

Python
styles = doc.Styles
st = styles.Add("PythonTitle", constants.wdStyleTypeParagraph)
st.Font.Size = 20
st.Font.Bold = True
st.ParagraphFormat.Alignment = constants.wdAlignParagraphCenter

11. 差し込み文書(Mail Merge)

テンプレートとデータソースを紐付ける

Python
doc = word.Documents.Open(r"C:\template.docx")
doc.MailMerge.OpenDataSource(
    Name=r"C:\data.xlsx",
    ConfirmConversions=False,
    ReadOnly=True
)

差し込み処理を実行

Python
doc.MailMerge.Execute()

12. コメント・変更履歴

コメントを追加

Python
doc.Comments.Add(doc.Range(0, 10), "ここを修正")

変更履歴をオンにする

Python
doc.TrackRevisions = True

履歴の一括承認/拒否

Python
doc.AcceptAllRevisions()
# doc.RejectAllRevisions()

13. 文書比較(Compare)

Python
doc1 = word.Documents.Open(r"C:\old.docx")
doc2 = word.Documents.Open(r"C:\new.docx")

result = word.CompareDocuments(doc1, doc2)
result.SaveAs(r"C:\comparison.docx")

14. その他:アプリケーション制御

警告を抑制

Python
word.DisplayAlerts = False

Word を安全に終了(finally)

Python
try:
    word = Dispatch("Word.Application")
    doc = word.Documents.Open(r"C:\doc.docx")

finally:
    doc.Close(SaveChanges=False)
    word.Quit()

まとめ

Word は Excel や Outlook と比べてもテンプレ書類が多く、自動化の効果が大きい分野です。

  • 契約書テンプレへ自動差し込み
  • Word → PDF 自動生成
  • 表・画像・図形・スタイル操作
  • 変更履歴・コメント・文書比較
  • MailMerge(差し込み文書)

まで、業務用書類の自動生成を Python で完結できます。

ぜひ、本記事の内容を参考に自動化に取り組んでみてください。

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

普段はエンジニアとして働きつつ、旅行では「住むように旅する」をテーマに動き回っています。

TABIGRAMMER では、
・旅の情報(台湾を中心としたアジア旅ガイド)
・ミニマリストの持ち物や旅の効率化テクニック
・ブログ運営やプログラミング記事

といった、旅とITが交差するコンテンツを発信しています。

難しいことをわかりやすく、旅をより快適に。そんなスタイルで記事を書いています。

コメント

コメントする

日本語が含まれない投稿は無視されますのでご注意ください。(スパム対策)