Last active
December 12, 2015 07:48
-
-
Save snipsnipsnip/4739030 to your computer and use it in GitHub Desktop.
win32oleつかってxlsをcsvに変換
This file contains hidden or 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
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