Class: Xls2Csv::Core

Inherits:
Object
  • Object
show all
Defined in:
lib/xls2csv/core.rb

Instance Method Summary collapse

Constructor Details

#initialize(xls, dir, logger = nil) ⇒ Core

Returns a new instance of Core.



7
8
9
10
11
12
# File 'lib/xls2csv/core.rb', line 7

def initialize(xls, dir, logger = nil)
  @xls = xls
  @dir = dir
  @logger = logger || Logger.new(STDOUT)
  Spreadsheet.client_encoding = 'UTF-8'
end

Instance Method Details

#convertObject



19
20
21
# File 'lib/xls2csv/core.rb', line 19

def convert
  read_xls.each {|filename, value| write_csv(filename, value)}
end

#read_xls(xls = @xls) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/xls2csv/core.rb', line 23

def read_xls(xls = @xls)
  raise Ole::Storage::FormatError unless File::extname(xls) == '.xls'

  csvs = Hash.new{|hash, key| hash[key] = []}
  Spreadsheet.open(xls).worksheets.each do |sheet|
    sheet.each {|row| csvs[sheet.name] << row_to_s(row)}
  end
  csvs
rescue Errno::ENOENT, Errno::EACCES
  @logger.info 'Reading ERROR!!!'
  @logger.info $!.message
rescue Ole::Storage::FormatError
  @logger.info 'Reading ERROR!!!'
  @logger.info "#{xls} is not xls-file."
end

#startObject



14
15
16
17
# File 'lib/xls2csv/core.rb', line 14

def start
  Xls2Csv::Options
  convert
end

#write_csv(filename, value) ⇒ Object



39
40
41
42
43
44
45
46
# File 'lib/xls2csv/core.rb', line 39

def write_csv(filename, value)
  File.open("#{@dir}/#{filename}.csv", 'w') do |f|
    value.each {|row| f.puts "\"#{row.join('","')}\""}
  end
rescue Errno::ENOENT, Errno::EACCES
  @logger.info 'Writing ERRER!!!'
  @logger.info $!.message
end