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
Scriptomがうまく動かない
Scriptomを使おうかなと思ったんだけど、エラーが出てしまってどうもうまく動かない…。
ちなみに、うちのPCにはGroovy 1.5.7 Windows-Installer版を使ってインストールしてあるので*1、Scriptomは最初から入ってるはずなんだが…。
以下の%GROOVY_HOME%\supplementary\Scriptom\examples.zipに入ってたIE.groovy*2を実行してみたんだが、だめでした。
import org.codehaus.groovy.scriptom.*; Scriptom.inApartment { def ie = new ActiveXObject('InternetExplorer.Application') ie.Visible = true ie.AddressBar = true ie.Navigate("http://glaforge.free.fr/weblog") }
結果
>groovy IE.groovy
Caught: java.lang.UnsatisfiedLinkError: D:\tool\Groovy\Groovy-1.5.7\bin\scriptom-1.5.4b11-x86.dll: このアプリケーションの構成が正しくないため、アプリケーションを開始できませんでした。アプリケーションを再度インストールすることにより問題が解決する場合があります。
at IE.run(IE.groovy:3)
at IE.main(IE.groovy)
dllの問題?msvcr80.dllあたりが悪さしているんだろうか…。何か進展があったら追記します。
2009-01-12追記
Scriptomのパッケージをここからダウンロードしてきて、zipを展開した中にあったドキュメント*3によると…*4
3. To avoid the dreaded java.lang.UnsatisfiedLinkError, download and install one of the following
updates from Microsoft: Microsoft Visual C++ 2005 SP1 Redistributable Package (x86)or Microsoft
Visual C++ 2005 SP1 Redistributable Package (x64).
ってことだったんで、
Download: Visual C++ 2005 SP1 Redistributable Package (x86) - Microsoft Download Center - Download Details
から再配布パッケージをダウンロードしてインストールしたら動きました。まったくマイクロソフトやれやれですね。これでやっとgroovyでCOMのスクリプトが書ける。