次はExcelシートをSQLで読み込んでみる。
 接続文字列が若干違うだけ。
 指定するSQLでは、シート名を From [Sheet1$] といった感じにする必要があるのでそのチェックを追加している。
    | param( [string]$dataSource  ,
 [string]$sqlCommand  ,
 [switch]${??}
 )
 $comment = @'
 #####################################################
 MRead-Excel.ps1 Excelデータを読み込む。
 param(
 [string]$dataSource  ,
 [string]$sqlCommand  ,
 [switch]${??}
 )
 例:
 # Excelファイルにアクセスする
 MRead-Excel.ps1 (Resolve-Path xls_test.xls) -Sql 'Select * from [Sheet1$]'
 #####################################################
 '@
 if(${??}) {$comment;return}
 if(!$dataSource) {Write-Warning "Please specify a datasource." ; return}
 if(!$sqlCommand) {Write-Warning "Please specify a query." ; return}
 #シート名が正しく指定されていない場合はエラーを発生させる if($sqlCommand -notmatch '\[.+\$\]')
 {
 $error = ‘シート名はこんな感じで指定してね: [Sheet1$]'
 Write-Error $error
 return
 }
 #接続文字列を準備する
 $connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=$dataSource;Extended Properties='Excel 12.0;';"
 #データソースに接続し開く $connection = New-Object System.Data.OleDb.OleDbConnection $connectionString
 $command = New-Object System.Data.OleDb.OleDbCommand $sqlCommand,$connection
 $connection.Open()
 #結果をフェッチし、接続を閉じる $adapter = New-Object System.Data.OleDb.OleDbDataAdapter $command
 $dataset = New-Object System.Data.DataSet
 [void]$adapter.Fill($dataset)
 $connection.Close()
 #クエリーからすべての行を返す $dataset.Tables | Select-Object -ExpandProperty Rows | Out-GridView
 | 
  
 
0 件のコメント:
コメントを投稿