Saturday, May 14, 2011

How do I use OpenOffice.org Calc with Watir for data-driven tests?

Similar to Excel and the rest of Microsoft Office, OpenOffice.org is enabled for automation using a COM/OLE-like interface called UNO. So here's a brief example of how to access your Excel or OpenOffice.org spreadsheet using UNO, the Ruby Windows OLE interface, and OpenOffice.org.

require "win32ole"

noArgs = []
file_uri = "file:///c:/test.ods"

serviceManager = WIN32OLE.new("com.sun.star.ServiceManager")
coreReflection = serviceManager.createInstance("com.sun.star.reflection.CoreReflection")
desktop = serviceManager.creatInstance("com.sun.star.frame.Desktop")
spreadsheet = desktop.loadComponentFromURL (file_uri, "_blank", 0, noArgs)
sheetsCollection = spreadsheet.Sheets
sheet1 = sheetsCollection.getByIndex(0)
cellA1Formula = sheet1.getCellByPosition(0, 0).Formula # Gets text or number or whatever is in the cell
cellA1NumericValue = sheet1.getCellByPosition(0, 0).Value # Gets numerical value of the cell
cell1A = sheet1.getCellByPosition(0, 0) # Gets cell 1A
cell1A.Formula = "Nathan Lane" # Sets the formula for cell 1A to "Nathan Lane"

No comments:

Post a Comment