PowerShell Excel ファイル出力

PowerShelldでExcelのファイル出力をするサンプルです。

# 実行中のパス取得/移動
Set-Location "C:\powershell\"

# エクセルファイル作成
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $False

# ワークブック作成
$book = $excel.Workbooks.Add()
$sheet = $excel.Worksheets.Item(1)

# 書きこみ
$sheet.Cells.Item( 1, 1) = "123456"

# 列を自動幅調整
$null = $sheet.Columns.AutoFit()

# 日時に応じて名前をつけて保存
# C:\powershellが存在すること。環境に応じてパスを書き換えてください。
$date = Get-Date
$book.SaveAs("C:\powershell\" + $date.ToString("yyyyMMdd_HHmmss_") + "powersell.xlsx")
# Excelを閉じる
$excel.Quit()
 
# プロセスを解放する
$excel = $null
[GC]::Collect()

Bookmark this on Yahoo Bookmark
Bookmark this on Google Bookmarks
Share on LinkedIn
LINEで送る
Pocket