# QueryTable03.rb.txt: ruby script (encoding: Windows-31J) # ExcelのQueryTable操作 z_query03.xls を出力 # webのtableを取り込む require "exlap" filename = "z_query03.xls" if test(?e, filename) # z_query03.xls が存在するなら削除 File.unlink(filename) end xl = Exlap.new xl.opens(filename) do |wb| ss = wb.fes # 空のシートを選択 ss.Name = "気象情報のシート" # ワークシート名 url = 'http://www.data.jma.go.jp/obd/stats/data/mdrr/synopday/data1s.html' table_index = nil # 取り込む表を特定しない(すべて取り込む) qt = ss.QueryTables.Add( 'Connection'=>"URL;#{url}", 'Destination'=>ss.Range("A1")) qt.Name = "気象情報" if table_index != nil qt.WebTables = table_index end qt.WebSelectionType = table_index ? XlSpecifiedTables : XlAllTables qt.WebFormatting = XlWebFormattingAll qt.SaveData = false # 「クエリテーブルをワークブックと一緒に保存」をしない qt.RefreshPeriod = 0 # 「定期的更新」の時間(0で無効) qt.BackgroundQuery = false qt.Refresh # クエリテーブルの更新 ss.range_autofit wb.save end xl.quit __END__ *table_indexについて  サンプル中の table_index は、web内の何番目のtableを取り込むかを指定するものです。  table_index が nil だと、総てのテーブルを取り込みます。各tableが別々のワークシートに記録されるのでなく、総て1つのワークシートに入ります。  table_index を "3" とすれば、3番目のtableだけが取り込まれます。"3,4" とすれば3番目と4番目の2つが取り込まれます。  これに関連するプロパティは、次の2つです。 qt.WebTables = table_index if table_index qt.WebSelectionType = table_index ? XlSpecifiedTables : XlAllTables  このWebSelectionTypeプロパティの値を XlEntirePage にすれば、tableでなくwebページ全体を取り込むとの指定になります。その場合は、WebTablesプロパティを指定しません。 *webの取込み時に関連するプロパティ ・qt.WebSelectionType = XlSpecifiedTables  取込みのタイプを指定。 XlSpecifiedTables 特定の表のみ XlAllTables Webの表を総て XlEntirePage Webページ全体 ・qt.WebTables = "3,4"  表の名前やインデックス番号のカンマ区切りリスト ・qt.WebFormatting = XlWebFormattingNone  取り込む書式情報等の範囲 XlWebFormattingNone 指定なし(デフォルト) XlWebFormattingRTF リッチテキスト XlWebFormattingAll HTML(セル結合等が反映される) ・qt.WebPreFormattedTextToColumns = true  Webページの
 タグ内にあるデータを列に区切る
・qt.WebSingleBlockTextImport = false
 trueだと、
タグ内にあるデータを一括処理する。falseなら連続する行からなるブロックとして取り込む。
・qt.WebConsecutiveDelimitersAsOne = true
 Webページの 
 タグ内のデータが複数の列に区切られる場合、trueだと連続する区切り文字を1つの区切り文字として扱う。falseならそのまま。
・qt.AdjustColumnWidth = false
 trueだと列幅の自動調整を行う。web取込みに直結するものではないが参考まで。