VB.NET Excelに画像を挿入し、サイズ 変更するサンプル

画像を挿入し、サイズ 変更するサンプルソース

 

Sub Main()

  Dim xlPictures As Excel.Pictures

  Try

    xlPictures = DirectCast(xlSheet.Pictures, Excel.Pictures)

    Dim xlPicture As Excel.Picture

    Try

      Dim imgPath As String

      imgPath = "画像のパスを指定する"

 

      Dim files As New ArrayList

      'imgPath以下のjpgファイルをすべて取得

      GetAllFiles(imgPath, "*.jpg;*.jpeg", files)

      If files.Count > 0 Then

        'とりあえず1ファイルだけ

        xlPicture = DirectCast(xlPictures.Insert(files(0)), Excel.Picture)

        'A1セルに貼り付け

        xlPicture.Left = DirectCast(xlSheet.Cells(1, "A"), Excel.Range).Left + 2

        xlPicture.Top = DirectCast(xlSheet.Cells(1, "A"), Excel.Range).Top + 2

        '画像サイズがA1:E1幅より大きければ画像サイズを変更する

        If xlPicture.Width > xlSheet.Range("A1:E1").Width - 2 Then

          '縦横比の調整

          xlPicture.Height = xlPicture.Height * (xlSheet.Range("A1:E1").Width - 2) / xlPicture.Width

          xlPicture.Width = xlSheet.Range("A1:E1").Width - 2

        End If

      End If

    Finally

      If Not xlPicture Is Nothing Then

        System.Runtime.InteropServices.Marshal.ReleaseComObject(xlPicture)

      End If

    End Try

  Finally

    If Not xlPictures Is Nothing Then

      System.Runtime.InteropServices.Marshal.ReleaseComObject(xlPictures)

    End If

  End Try

End Sub

 

'folderにあるファイルを取得する

Private Sub GetAllFiles(ByVal folder As String, ByVal searchPattern As String, ByRef files As ArrayList)

  Try

    For Each extension As String In searchPattern.Split(";")

      Dim fs As String() = System.IO.Directory.GetFiles(folder, extension)

      'ArrayListに追加する

      files.AddRange(fs)

    Next

  Catch UAEx As UnauthorizedAccessException

    Console.WriteLine(UAEx.Message)

  Catch PathEx As PathTooLongException

    Console.WriteLine(PathEx.Message)

  End Try

End Sub

 

 

 http://hanatyan.sakura.ne.jp/patio/read.cgi?mode=view2&f=319&no=13

 http://ap.atmarkit.co.jp/bbs/core/fdotnet/16028

 http://detail.chiebukuro.yahoo.co.jp/qa/question_detail/q1431444399