酢ろぐ!

カレーが嫌いなスマートフォンアプリプログラマのブログ。

Excelシートをプリンタドライバを利用してtiff画像でファイル出力する

Office2003をインストールしていると、導入される仮想プリンタドライバ「Microsoft Office Document Image Writer」を使用して、Excelファイルの任意のシートを、tiff画像としてファイル出力します。

ソリューションエクスプローラ等から参照の追加を選択し、COMタブの「Microsoft Excel 11.0 Object Library」を追加します。

    ''' <summary>
    ''' Tiff画像を出力します
    ''' </summary>
    ''' <param name="inputExcelFilePath">入力するExcelのパス</param>
    ''' <param name="sheetNum">出力するシートのシートNo</param>
    ''' <param name="outTiffFilePath">出力するTiff画像のパス</param>
    ''' <remarks></remarks>
    Private Sub OutputTiff(ByVal inputExcelFilePath As String, _
                           ByVal sheetNum As Integer, _
                           ByVal outTiffFilePath As String)

        Dim app As Excel.Application = Nothing
        Dim books As Excel.Workbooks = Nothing
        Dim book As Excel.Workbook = Nothing
        Dim sheets As Excel.Sheets = Nothing
        Dim sheet As Excel.Worksheet = Nothing

        Try
            app = New Excel.Application

            books = app.Workbooks
            book = books.Open(inputExcelFilePath)
            sheets = book.Sheets
            sheet = sheets(sheetNum)

            ' プリンタドライバを使ってtiff画像を出力する
            sheet.PrintOut(Type.Missing, Type.Missing, 1, False, _
                           "Microsoft Office Document Image Writer", _
                           True, False, outTiffFilePath)

        Finally

            System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet)
            sheet = Nothing
            System.Runtime.InteropServices.Marshal.ReleaseComObject(sheets)
            sheets = Nothing

            book.Close(False)
            System.Runtime.InteropServices.Marshal.ReleaseComObject(book)
            book = Nothing

            books.Close()
            System.Runtime.InteropServices.Marshal.ReleaseComObject(books)
            books = Nothing

            app.Quit()
            System.Runtime.InteropServices.Marshal.ReleaseComObject(app)
            app = Nothing

        End Try
    End Sub