Class: CsvXlsxConverter::XlsxToCsv

Inherits:
Object
  • Object
show all
Defined in:
lib/csv_xlsx_converter/converter.rb

Instance Method Summary collapse

Constructor Details

#initialize(input_file) ⇒ XlsxToCsv

Returns a new instance of XlsxToCsv.

Raises:

  • (ArgumentError)


32
33
34
35
# File 'lib/csv_xlsx_converter/converter.rb', line 32

def initialize(input_file)
  raise ArgumentError, "input file is not xlsx" unless CsvXlsxConverter::xlsx_filename? input_file
  @input_file = input_file
end

Instance Method Details

#convert(output_file) ⇒ Object

Raises:

  • (ArgumentError)


37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/csv_xlsx_converter/converter.rb', line 37

def convert(output_file)
  raise ArgumentError, "output file is not csv" unless CsvXlsxConverter::csv_filename? output_file

  CSV.open(output_file, "wb") do |csv|
    workbook = RubyXL::Parser.parse @input_file
    worksheet = workbook[0]

    worksheet.each_with_index do |row, row_idx|
      row_data = []
      (0...row.size).each do |col_idx|
        cell = row[col_idx]
        row_data << cell.value
      end
      csv << row_data
    end
  end
end