yashiganiの英傑になるまで死ねない日記

週末はマスターバイクでハイラルを走り回ります

.NET から Excel をさわるのはまわりくどい

最近 VB.NET から Excel で出力するためのコードを書いていたんだけど,Excel を使うための手順が多すぎる
Excel のファイルに書き込むために

Excel アプリケーションの起動 -> ブックの集合の起動 -> ブックを起動 -> シートの集合を起動 -> シートを選択

みたいに気が遠くなる手順を踏まなければならない


もちろん終了するときには,これと逆順にオブジェクトをリリースしてやらないと Windows のプロセスに Excel が残ったりして後で困ることになる
直接いじってると発狂しそうになったのでラップしてやった

Public Class ExcelObject
    Friend app As Excel.Application
    Friend books As Excel.Workbooks
    Friend book As Excel.Workbook
    Friend sheets As Excel.Sheets
    Friend sheet As Excel.Worksheet

    Sub New(ByVal filename As String)
        Me.app = New Excel.Application
        Me.books = app.Workbooks
        Try
            Me.book = books.Open(filename)
        Catch ex As Exception
            Me.book = books.Add
        End Try
        Me.sheets = book.Sheets
        Me.sheet = CType(sheets(1), Excel.Worksheet)
    End Sub

    Sub Release()
        If Not Me.sheet Is Nothing Then
            System.Runtime.InteropServices.Marshal.ReleaseComObject(Me.sheet)
        End If
        If Not Me.sheets Is Nothing Then
            System.Runtime.InteropServices.Marshal.ReleaseComObject(Me.sheets)
        End If
        If Not Me.book Is Nothing Then
            System.Runtime.InteropServices.Marshal.ReleaseComObject(Me.book)
        End If
        If Not Me.books Is Nothing Then
            System.Runtime.InteropServices.Marshal.ReleaseComObject(Me.books)
        End If
        If Not Me.app Is Nothing Then
            System.Runtime.InteropServices.Marshal.ReleaseComObject(Me.app)
            app = Nothing
        End If
    End Sub
End Class

New したり Release したりするだけで用意と片付けができて便利
セルをつかったりするのも

Dim excel As New ExcelObject()

excel.app.visible = True ' Excel アプリケーションの表示
Dim Cell As Range = excel.sheet.Cells("A1")
Cell.value = "yashigani" ' A1セルに"yashigani"と表示

みたいな感じに書ける
というかもともとこういう設計にすべきだと思うんだけど,なにか理由があるのかな?


にしても .NET ってのは読みやすいリファレンスが無くて情報を得にくい
Visual Studio はよくできたというかやたら面倒みてくれる IDE だからなんとかなるんだけど,そのへんをしっかりしないとギークの心は掴めないと思う