Insert bitmap into Excel using VB.NET

H_D

New member
Joined
Nov 5, 2003
Messages
1
I need to insert a bitmap image into an excel (2000) spreadsheet. Ive been able to insert the picture into the shapes collection but cant figure out how to get it into a cell on the spreadsheet. Ive extensively searched the web for examples and havent had much luck...does anyone have experience with this? Any help would be much appreciated!
 
heres a quick example i knocked up , it took me a few minutes to realise that icons arent allowed , so the icon i tried, i changed to a bitmap.
you need a reference to the Excel object library...
Code:
        Dim xlApp As New excel.ApplicationClass() /// reference to Excel object library.
        Dim xlBook As excel.Workbook = xlApp.Workbooks.Open("F:\Book1.XLS")
        Dim xlSheet As excel.Worksheet = xlBook.Worksheets("Sheet1")

        Clipboard.SetDataObject(Me.Icon.ToBitmap()) /// in this case i set the forms icon as a bitmap , then copied to the clipboard.

        xlSheet.Range("A2").Select() /// select the cell to paste to

        xlBook.ActiveSheet.PasteSpecial(Format:="Bitmap", Link:=False, DisplayAsIcon:=True) /// paste the image in to the cell

        xlBook.Save() /// save the changes.
        xlApp.Quit()
 
The code below should work (this is line by line translation from VBA). Unfortunately I cant test it because Im getting problem with MS Excel Interop.Excel.dll :(

Dim xapp As Excel.Application
Dim wbk As Excel.Workbook
Dim wks As Excel.Worksheet
Dim rng As Excel.Range
Dim pic As Object Excel.Picture
Dim strPictureFillPath As String

xapp = New Excel.Application()
xapp = CreateObject("Excel.Application.9")
dont forget to create test workboomk and save it in c:\temp\book1.xls
wbk = xapp.Workbooks.Open("c:\temp\book1.xls")
wks = xapp.Worksheets(1)
rng = wks.Cells(3, 3) Lets put the picture in the cell(3,3)
rng.Select()
this is a sample picture
strPictureFillPath = "C:\Documents and Settings\Administrator\My Documents\My Pictures\Sample.jpg"
wks.Pictures.Insert(strPictureFillPath).Select()
pic = xapp.Selection
With pic
.Name = "My Picture"
.Left = rng.Left
.Top = rng.Top
.Width = rng.Width
.Height = rng.Height
.Placement = 1 xlMoveAndSize
.PrintObject = True
.Locked = True
End With

wbk.Save()
xapp.Quit()
xapp = Nothing

HTH,
Shamil
 
I tested the code it works. The problem with Interop.Excel.Dll solved using info from http://support.microsoft.com/?kbid=320369 - I just added before the code:

save default culture information
Dim oldCI As System.Globalization.CultureInfo = _
System.Threading.Thread.CurrentThread.CurrentCulture

System.Threading.Thread.CurrentThread.CurrentCulture = _
New System.Globalization.CultureInfo("en-US")

and after the code:

restore default culture information
System.Threading.Thread.CurrentThread.CurrentCulture = oldCI

HTH,
Shamil
 
Back
Top