| name | com-automation |
| description | Windows COM Automation for Office applications (Word, Excel, Outlook) and Shell.Application. Integrates WinClaw PowerShell COM recipes. Use for document creation, email automation, and Office batch operations. |
| version | 1.0.0 |
| sources | ["https://github.com/itc-ou-shigou/winclaw"] |
COM Automation Skill
適用場景
- Excel:批次讀寫、公式計算、圖表生成
- Word:文件建立、範本填充、格式轉換
- Outlook:郵件發送、行事曆操作、聯絡人管理
- Shell.Application:桌面互動、壓縮/解壓縮
不適用: 非 Office 程式(改用 gui-automation)
Excel 操作
# 開啟或建立 Excel 檔案
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $false
$excel.DisplayAlerts = $false
try {
$workbook = $excel.Workbooks.Open("C:\data\report.xlsx")
$sheet = $workbook.Sheets.Item(1)
# 讀取儲存格
$value = $sheet.Cells.Item(1, 1).Value2
# 寫入資料
$sheet.Cells.Item(2, 1).Value2 = "自動填入"
$sheet.Cells.Item(2, 2).Value2 = Get-Date -Format "yyyy-MM-dd"
$workbook.Save()
}
finally {
$workbook.Close($false)
$excel.Quit()
[System.Runtime.InteropServices.Marshal]::ReleaseComObject($excel) | Out-Null
[System.GC]::Collect()
}
Word 操作
$word = New-Object -ComObject Word.Application
$word.Visible = $false
try {
$doc = $word.Documents.Add()
$selection = $word.Selection
# 標題
$selection.Style = $doc.Styles.Item("Heading 1")
$selection.TypeText("自動產生報告")
$selection.TypeParagraph()
# 內文
$selection.Style = $doc.Styles.Item("Normal")
$selection.TypeText("產生時間:$(Get-Date)")
$doc.SaveAs2("C:\output\report.docx")
}
finally {
$doc.Close()
$word.Quit()
[System.Runtime.InteropServices.Marshal]::ReleaseComObject($word) | Out-Null
}
Outlook 郵件
$outlook = New-Object -ComObject Outlook.Application
$mail = $outlook.CreateItem(0) # 0 = olMailItem
try {
$mail.To = "recipient@example.com"
$mail.Subject = "自動化報告"
$mail.Body = "請見附件。"
$mail.Attachments.Add("C:\output\report.xlsx")
$mail.Send()
}
finally {
[System.Runtime.InteropServices.Marshal]::ReleaseComObject($mail) | Out-Null
[System.Runtime.InteropServices.Marshal]::ReleaseComObject($outlook) | Out-Null
}
Shell.Application
# 壓縮資料夾
$shell = New-Object -ComObject Shell.Application
$zipPath = "C:\output\archive.zip"
New-Item -ItemType File -Path $zipPath -Force | Out-Null
$zip = $shell.NameSpace($zipPath)
$source = $shell.NameSpace("C:\data\")
$zip.CopyHere($source.Items())
[System.Runtime.InteropServices.Marshal]::ReleaseComObject($shell) | Out-Null
安全規則
- 永遠使用
try/finally 釋放 COM 物件
- 呼叫
ReleaseComObject + GC.Collect() 避免記憶體洩漏
- 大量操作前 設
ScreenUpdating = $false
- Outlook 發送前 預覽確認收件人與附件
參考資料
references/excel.md — Excel 進階操作
references/word.md — Word 文件處理
references/outlook.md — Outlook 郵件與行事曆
references/shell-application.md — Shell.Application 用法
examples/excel-batch-edit.ps1 — Excel 批次範例
examples/outlook-triage.ps1 — Outlook 郵件分類範例