Groovyでエンティティ定義書からデータ抜き出し

今のプロジェクトでは ER図専用ソフト で作っています。

今回のテーマ

それでもわざわざ、ソフトが出力するフォーマットとは異なるエクセルファイルに書き出さないといけないということが多々あるのが この業界の常 (?)。

javaでエクセルファイルを操作するためのライブラリとして有名なのが Apache POI です。 これをgroovyから使ってみようというのが今回のテーマ。

下がそのサンプルです。

検証環境

スクリプトの上段のあたりを見ていただければ分かる通り、Windowsです。 ( “c:/” というCドライブ指定のパスが分かりますね。 )

作成したスクリプト

createColumnDictionary.groovy

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import java.io.*
import org.apache.poi.hssf.usermodel.*
import org.apache.poi.poifs.filesystem.*

def text = ""
def workdir = new File("c:/")

def tables = []
workdir.listFiles().findAll { it.name.contains("エンティティ定義書_") }.each {
    def table = new Table()

    def fs = new POIFSFileSystem(new FileInputStream(it.path));
    book = new HSSFWorkbook(fs);
    def sheet = book.getSheetAt(0)
    def cell = { row, col -> sheet.getRow(row)?.getCell((short) col) }

    table.physicalName = cell(3, 0).stringCellValue.toUpperCase()
    def keys = []

    for (i in 7..100) {
        if (!(!cell(i, 1)?.stringCellValue)) {
            def column = new Column()

            //自動的な折り返しの設定
            column.logicalName = cell(i, 1)?.stringCellValue
            column.physicalName = cell(i, 2)?.stringCellValue
            column.type = cell(i, 3)?.stringCellValue
            column.length = (cell(i, 4)?.numericCellValue) ? cell(i, 4)?.numericCellValue.intValue().toString() : ""
            def seido = (cell(i, 5)?.numericCellValue) ? cell(i, 5)?.numericCellValue.intValue() : 0
            if (column.type.equalsIgnoreCase("NUMBER")) column.length += "," + seido
            column.notNull = cell(i, 6)?.stringCellValue
            column.primaryKey = (cell(i, 7)?.numericCellValue?.intValue()) ?: ""

            table.columns << column
        }
    }

    tables << table
}

def lines = []
tables.each {
    lines += it.physicalKeys
}

new File("${workdir}/columns.txt").write(lines.sort().join("n"))

Table.groovy

class Table {
    def columns = []
    def physicalName = ""
    def logicalName = ""

    def getPhysicalKeys() {
        def keys = []
        columns.each {
            keys << """${this.physicalName}|${it.physicalKey}"""
        }

        keys
    }
}

Column.groovy

class Column {
    def physicalName = ""
    def logicalName = ""
    def type = ""
    def length = ""
    def notNull = ""
    def primaryKey = ""

    def getPhysicalKey() {
        """${this.physicalName}|${this.type}|${this.length}|${this.notNull}|${this.primaryKey}"""
    }
}

指定されたフォルダのエンティティ定義書(エクセル)をすべて読み込んでテキストに出力しています。 クロージャの使い方がポイント。 metaClass を使用して、 Apache POI 自体のworkbookオブジェクトにcellメソッド追加とかしても面白いかもしれないです。