Created
October 3, 2012 18:09
-
-
Save urara/3828692 to your computer and use it in GitHub Desktop.
Excelからの読み込み、書き出し http://jp.rubyist.net/magazine/?0004-Win32OLE
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! ruby -Ks | |
# -*- coding: sjis -*- | |
require 'win32ole' | |
module Worksheet | |
def [] y,x | |
cell = self.Cells.Item(y,x) | |
if cell.MergeCells | |
cell.MergeArea.Item(1,1).Value | |
else | |
cell.Value | |
end | |
end | |
def []= y,x,value | |
cell = self.Cells.Item(y,x) | |
if cell.MergeCells | |
cell.MergeArea.Item(1,1).Value = value | |
else | |
cell.Value = value | |
end | |
end | |
end | |
def getAbsolutePath filename | |
fso = WIN32OLE.new('Scripting.FileSystemObject') | |
return fso.GetAbsolutePathName(filename) | |
end | |
def openExcelWorkbook filename | |
filename = getAbsolutePath(filename) | |
xl = WIN32OLE.new('Excel.Application') | |
xl.Visible = true | |
book = xl.Workbooks.Open(filename) | |
begin | |
yield book | |
ensure | |
xl.Workbooks.Close | |
xl.Quit | |
end | |
end | |
app = WIN32OLE.new('Excel.Application') | |
book = app.Workbooks.Open("C:\\work\\ruby\\test.xls") | |
#使っているワークシート範囲を一行ずつ取り出す | |
for row in book.ActiveSheet.UsedRange.Rows do | |
#取り出した行から、セルを一つづつ取り出す | |
for cell in row.Columns do | |
p cell.Address | |
p cell.Value | |
p '-------' | |
end | |
end | |
book.close(false) | |
app.quit | |
#Excelに書き出し | |
openExcelWorkbook("test.xls") do |book| | |
sheet = book.Worksheets.Item(1) | |
sheet.extend Worksheet | |
sheet[1,4] = "English" | |
sheet[2,4] = 5 | |
book.Save | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment