ScriptomでExcelファイルの内容の読み込み
Excelで作ったアンケートの集計に使いたかっただけなので、ひとまず値を読み取るだけのサンプルを作成してみた。
準備
セルA1〜A10に「○」という文字がいくつか記入されているExcelファイルを用意する。(例: test1.xls〜test3.xls)
Groovyスクリプトをtest1.xls〜test3.xlsと同じフォルダに置き、実行。
Groovyスクリプトのソース
import org.codehaus.groovy.scriptom.* Scriptom.inApartment { def excel = new ActiveXObject('Excel.Application') def fileNames = (1..3).collect{ "test${it}.xls" } def allValues = [] fileNames.each{ // ファイルを開く excel.workbooks.open(new File(it).canonicalPath) // セルに対しての操作 def values = [] excel.sheets(1).cells.with{ for (r in 1..10) { values << cells.item(r, 1).value } } println "${it} ${values.count('○')}count." allValues.addAll(values) // ファイルを閉じる excel.quit() } println "all ${allValues.count('○')} count." }
セルA1〜A10の値を順繰りにリストに投入してあとで「○」の数を数えてます。
ちなみに、Scriptom.inApartmentは、COMスレッドのハンドリングをうまい具合にやってもらうためのおまじないかな?
Wrap any code that references an ActiveXObject in Scriptom.inApartment { ... }, which replaces the way Scriptom previously handled COM threading.
Groovy - COM Scripting
実行結果
test1.xls 3count.
test2.xls 4count.
test3.xls 5count.
all 12 count.
こんな感じでちゃんと動いていることが確認できた。よしよし。
動作確認したバージョン
Groovy Version: 1.5.7 JVM: 1.6.0_10Scriptom-1.5 (dlls in bin, jars in lib)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
bin:
msvcr80.dll
scriptom-1.5.4b11-32.dll
scriptom-1.5.4b11-64.dll
lib:
scriptom-1.5.4b11.jar
supplementary/Scriptom:
examples.zip tlbinf32.zip