Ruby & Excel: Inserting Pictures Into Cells (New and Improved!)
In a previous article, I discussed a method for inserting images into an Excel worksheet. It seems that the Worksheet.Pictures.Insert() method that I demonstrated in that article, though frequently used, is not actually officially documented in the Excel Object Model Reference. An astute reader has called my attention to this fact and, in reply, I hereby present the officially documented---and probably preferred---method for adding an image to a worksheet.
The Worksheet object's Shapes collection includes an AddPicture() method that creates a picture from an existing file and returns a Shape object that represents the new picture. The syntax is:
.AddPicture(Filename, LinkToFile, SaveWithDocument, Left, Top, Width, Height)
All seven arguments are required, but this allows you to specify the position and size of the picture in the method call.
The following code inserts an image into the range of cells from C3 to F5 in the active worksheet:
require 'win32ole'
xl = WIN32OLE.connect('Excel.Application')
ws = xl.ActiveSheet
range = ws.Range('C3:F5')
pic = ws.Shapes.AddPicture( {
'FileName' => 'C:\Pictures\Image1.jpg',
'LinkToFile' => false,
'SaveWithDocument' => true,
'Left' => range.Left,
'Top' => range.Top,
'Width' => range.Width,
'Height' => range.Height
} )
You can find further details on the AddPicture() method on MSDN.
My thanks to Charles Roper for his inquiry, prompting me to dig a little deeper.
And my thanks to you for stopping by!
- Operating System:
- Person:
- Programming Language:
- Tags:


Recent comments
1 year 23 weeks ago
1 year 23 weeks ago
1 year 25 weeks ago
1 year 27 weeks ago
1 year 42 weeks ago
1 year 45 weeks ago
1 year 45 weeks ago
1 year 45 weeks ago
1 year 46 weeks ago
1 year 48 weeks ago