前置條件
- Windows 環境
- 安裝 Microsoft Word
pip install pywin32
核心操作範例
import win32com.client
from win32com.client import constants
def automate_word(input_path, output_path):
# 建立 Word 應用程式物件
word = win32com.client.Dispatch('Word.Application')
# 或 DispatchEx 建立獨立進程
word.Visible = False # 後台執行
word.DisplayAlerts = False # 抑制警告對話框
try:
doc = word.Documents.Open(input_path)
# 1. 插入文字
rng = doc.Range(0, 0)
rng.InsertBefore('Hello from Python!')
rng.Style = constants.wdStyleHeading1
# 2. 正文文字替換
word.Selection.Find.ClearFormatting()
word.Selection.Find.Replacement.ClearFormatting()
word.Selection.Find.Execute(
'OldStr', False, False, False, False, False, True, 1, True, 'NewStr', 2
)
# 3. 頁眉替換
header = doc.Sections[0].Headers[0].Range
header.Find.ClearFormatting()
header.Find.Replacement.ClearFormatting()
header.Find.Execute('OldStr', False, False, False, False, False, True, 1, False, 'NewStr', 2)
# 4. 表格操作
if doc.Tables.Count > 0:
table = doc.Tables[0]
table.Rows[0].Cells[0].Range.Text = '123123'
table.Rows.Add() # 新增列
# 5. 匯出為 HTML
doc.WebOptions.RelyOnCSS = True
doc.WebOptions.OptimizeForBrowser = True
doc.WebOptions.BrowserLevel = constants.wdBrowserLevelV4
doc.WebOptions.AllowPNG = True
doc.SaveAs(output_path, FileFormat=constants.wdFormatHTML)
# 6. 列印
# doc.PrintOut()
finally:
doc.Close(constants.wdDoNotSaveChanges)
word.Quit()
if __name__ == '__main__':
automate_word('input.docx', 'output.html')
關鍵物件模型
| 物件 | 用途 |
| Application | Word 應用程式總控 |
| Document | 單一 .doc/.docx 文件 |
| Range | 文件連續區域,核心操作單元 |
| Selection | 使用者選取區域(含游標位置) |
| Find/Replacement | 尋找/替換設定 |
| Tables/Rows/Cells | 表格結構操作 |
| Shapes/InlineShapes | 圖片、圖表、藝術字等 |
常見問題與解決
- 殘留進程:務必在
finally 中 Quit(),若卡死需強制殺掉 WINWORD.EXE。
- 版本相容:不同 Office 版本常數可能不同,優先使用
constants 模組。
- 效能:COM 呼叫開銷大,批量操作建議關閉螢幕更新
word.ScreenUpdating = False。
- 跨平台替代:
python-docx(純 Python,僅 .docx,無需 Word)、LibreOffice headless 模式轉檔。