Wednesday, August 5, 2009

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!

1 comment:

Anonymous said...

Hi,

I am facing bellow error while using Shapes.AddPicture

Error:
C:/Users/Charvitha_K/RubymineProjects/Ruby POC/support/env.rb:1221:in `method_missing': (in OLE method `AddPicture': ) (WIN32OLERuntimeError)
OLE error code:0 in

HRESULT error code:0x8002000f
Parameter not optional.
from C:/Users/Charvitha_K/RubymineProjects/Ruby POC/support/env.rb:1221:in `'
from -e:1:in `load'
from -e:1:in `'










Code used is:
require "watir"
require "win32ole"
require 'rubygems'
require 'open-uri'
require 'spreadsheet'
require 'rubyXL'
require 'roo'
require 'win32ole'

@excel = WIN32OLE::new("excel.Application")
@workbook = @excel.Workbooks.Open("D:\\TestData.xls")
worksheet = @workbook.WorkSheets(1)

@pic = worksheet.Shapes.AddPicture( {
# 'FileName' => 'C:\Pictures\Image1.jpg',
'FileName' => "#{@F1}",
'LinkToFile' => false,
'SaveWithDocument' => true,
'Left' => @left1,
'Top' => @Top1,
'Width' => @Width1,
'Height' => @Height1
} )
@F1 = "D:\1.jpg"
@pic = worksheet.Pictures.Insert('D:\1.jpg')
@range = worksheet.Range('C3:F5')
@Top1 = 100
@left1 = 100
@pic.ShapeRange.LockAspectRatio = false
@pWidth1 = 400
@Height1 = 300