#navi(../)
* PowerShellでExcelファイルを操作する方法 [#wd7df207]
PowerShellでExcelファイル内の内容を読み込み表示するサンプルスクリプトを以下に記します。

#contents
#htmlinsertpcsp(win-top.html,win-sp.html)


* 使用したExcelブック [#xa4366fa]
以下のように3つの列に値を入れたExcelファイルを作成しました。
#ref(01.png)

* 作成したExcelを読み込むPowerShellスクリプト [#l6384a81]
#ref(readexcel.ps1)
 param($file)
 
 # パラメタチェック
 if ($file -eq $null) {
   $thie = $MyInvocation.MyCommand.Name
   "Usage: $this <Excel file>"
   exit 1
 }
 
 # Excelファイルの有無チェック
 if (!(Test-Path $file)) {
   Write-Host $file not found.
   exit 1
 }
 
 try {
     $file = (Get-ChildItem $file).FullName
     $excel = New-Object -ComObject Excel.Application
     $excel.Visible = $false    # <- Excel非表示
     $book = $excel.Workbooks.Open($file)
     $sheet = $excel.Worksheets.Item(1)   # <- 1番目のシートを選択
     $line = 1
     while ($true) {
         $item1 = $sheet.Cells.Item($line,1).Text
         $item2 = $sheet.Cells.Item($line,2).Text
         $item3 = $sheet.Cells.Item($line,3).Text
         if ($item1 -eq "") { berak }   # <- 空のセルを見つけたら終了
         Write-Host "$item1, $item2, $item3"    # <- 取得した情報を表示
         $line++
     }
 } catch [Exception] {
     $exp = $error[0].ToString()
 } finally {
     $excel.Quit()
 }

*スクリプト実行結果 [#sa5a6fe1]
 PS D:\> .\readexcel.ps1 .\ExcelBook.xlsx
 No, TYPE, OSNAME
 1, Win, Windows 95
 2, Win, Windows 98
 3, Win, Windows 2000
 4, Win, Windows XP
 5, Win, Windows 7
 6, Win, Windows 10
 7, Linux, Ubuntu
 8, Linux, CentOS
 9, BSD, FreeBSD
 10, BSD, OSX

以上、PowerShellでExcelシートの内容を読み込むサンプルスクリプトでした。

#htmlinsertpcsp(win-btm.html,win-sp.html)

トップ   編集 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS