Skip to content

Instantly share code, notes, and snippets.

@snipsnipsnip
Last active December 12, 2015 07:48
Show Gist options
  • Save snipsnipsnip/4739030 to your computer and use it in GitHub Desktop.
Save snipsnipsnip/4739030 to your computer and use it in GitHub Desktop.
win32oleつかってxlsをcsvに変換
require 'win32ole'
require 'tempfile'
class Xls2csv
def self.main(argv=ARGV)
open do |x|
ARGV.each do |from|
dot = from.rindex('.')
to = "#{dot ? from[0...dot] : from}.csv"
x.convert(from, to)
end
end
end
def self.open
x = new
yield x
ensure
x.close
end
def initialize
@excel = WIN32OLE.new('Excel.Application')
@consts = Module.new
WIN32OLE.const_load(@excel, @consts)
end
def close
@excel.quit
end
def convert(xls, out)
xls = calc_absolute(xls)
out = calc_absolute(out)
book = @excel.workbooks.open(xls, true)
book.activesheet.saveas(out, @consts::XlCSV)
ensure
book.close(false)
end
def with_csv(xls)
Tempfile.open(['xls2csv.', '.csv']) do |f|
path = f.path
f.close!
convert(xls, path)
yield path
end
end
private
def calc_absolute(path)
File.expand_path(path).gsub('/',"\\")
end
end
Xls2Csv.main if __FILE__ == $0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment