使用Ruby& amp;修改后无法保存Excel文件WIN32OLE

时间:2011-07-19 20:58:16

标签: ruby excel win32ole

使用http://ruby-doc.org/stdlib/libdoc/win32ole/rdoc/classes/WIN32OLE.html作为指导我写了以下内容:

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()

当我在所有这些之后打开Excel电子表格时它没有改变。有什么想法吗?

1 个答案:

答案 0 :(得分:3)

Saved对象的Workbook属性设置为True不会导致保存工作簿。该属性用作标志以显示工作簿是否具有未保存的更改。将其设置为True是一种简单的方法,可以防止Excel关闭时出现“您是否要保存...”对话框。

要实际保存工作簿,您需要Save对象的Workbook方法。这个方法没有返回任何东西,所以我认为workbook.Save可以做到这一点(不幸的是,我没有Ruby的经验,所以不能100%肯定)