Using http://ruby-doc.org/stdlib/libdoc/win32ole/rdoc/classes/WIN32OLE.html as a guide I have written the following:
require 'win32ole'
excel = WIN32OLE.new('Excel.Application')
excel.visible = false #Setting this is 'true' doesn't reveal anything
workbook = excel.workbooks.open('C:\myspreadsheet.xlsx')
worksheet = workbook.worksheets('sheet1')
worksheet.Activate
data = worksheet.UsedRange.Value
p data.size #This works! - My spreadsheet has 3987 rows.
p data[3932] #This works, too! - I can "see" row 3932.
worksheet.Rows(3932).Insert #Insert a row above row 3932
data = worksheet.UsedRange.Value
p data.size #Returns 3988! This would seem to indicate that I've successfully added a row since it was just 3987.
workbook.saved = true #Save the workbook and quit.
excel.ActiveWorkbook.Close(0)
excel.Quit()
When I open the Excel spreadsheet after all of this it is unchanged. Any ideas?
Setting the
Savedproperty of aWorkbookobject toTruedoes not cause the workbook to be saved. That property is used as a flag to show whether a workbook has unsaved changes. Setting it toTrueis a simple way of preventing the “Do you wish to save…” dialog appearing when Excel is closed.To actually save the workbook, you need the
Savemethod of theWorkbookobject. This method doesn’t return anything so I would assume thatworkbook.Savewould do the trick (I have no experience of Ruby, unfortunately, so can’t be 100% sure on that)