たくさんファイルがあって、特定のシート、列の表から値を抜き取り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