LoginSignup
1
4

More than 5 years have passed since last update.

powershellでexcelから情報抜き取る

Posted at

たくさんファイルがあって、特定のシート、列の表から値を抜き取りcsvにしたい場合に
思い立って作った処理です。

変数の定義箇所に疑問あるがとりあえず、備忘録として。。。(今後メンテすることないけど)

$excel = New-Object -ComObject Excel.Application
$excel.Visible = $false
$excel.DisplayAlerts = $false

function getRowValuesFromExcel ($ExcelFileName) {
  $basePath = "\path\to\dir\"
  # open read only
  $book = $excel.Workbooks.Open($basePath + $ExcelFileName ,0 ,$true)
  $sheet = $book.WorkSheets.item("hoge_sheet")

  # 1~100行のB,C,D,E列の情報をカンマ区切りで出力
  $firstRowIdx = 1
  $MaxRowIdx = 100
  $RowIdx = $firstRowIdx
  while ($RowIdx -lt $MaxRowIdx )
  {
    # 書式など維持した状態で取得は Text, 値のみはValue()
    $B = $sheet.Range("B" + $RowIdx).Text
    $C = $sheet.Range("C" + $RowIdx).Value()
    $D = $sheet.Range("D" + $RowIdx).Value()
    $E = $sheet.Range("E" + $RowIdx).Value()

    Write-Output @"
$B,$C,$D,$E
"@
    $RowIdx++
  }
}

getRowValuesFromExcel("hoge1.xls")
getRowValuesFromExcel("hoge2.xls")
getRowValuesFromExcel("hoge3.xls")

return 0

1
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
4