Ruby で Excel

Excel ファイルを 作成する

lesson006.rb


require 'win32ole'

objExcel = WIN32OLE.new('Excel.Application')
objExcel.Visible = 1
objExcel.DisplayAlerts = 0 #警告メッセージをOFF

begin
#ブックを読み取り専用で開く
bookIn = objExcel.WorkBooks.Open(ARGV[0])

begin
#ブックを書き込み用で開く
bookOut = objExcel.Workbooks.Add

#いったん、シートを1枚だけにする
iSheet = bookOut.WorkSheets.Count
while iSheet > 1
bookOut.WorkSheets(iSheet).Delete
iSheet -= 1
end

for iSheet in 1..bookIn.WorkSheets.Count do
#必要なら、シートを追加する
bookOut.Sheets.Add(nil, bookOut.WorkSheets(iSheet - 1)) if (iSheet > bookOut.WorkSheets.Count)

sheetIn = bookIn.WorkSheets(iSheet)
sheetOut = bookOut.WorkSheets(iSheet)

#シート名を変更する
sheetOut.Name = sheetIn.Name if (sheetOut.Name != sheetIn.Name)

#データをコピーする
for iRow in 1..sheetIn.Cells.CurrentRegion.Rows.Count do
for iCol in 1..sheetIn.Cells.CurrentRegion.Columns.Count do
sheetOut.Cells(iRow, iCol).Value = sheetIn.Cells(iRow, iCol).Value
end
end
end

#ブックを保存する
bookOut.SaveAs(ARGV[1])
ensure
bookOut.Close
end
ensure
bookIn.Close
objExcel.Quit
end

実行結果

C:\>ruby c:\study\ruby\chapter004\lesson006.rb c:\study\Book1.xls c:\study\Book2
.xls