Class: CsvXlsxConverter::CsvToXlsx

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

Instance Method Summary collapse

Constructor Details

#initialize(input_file) ⇒ CsvToXlsx

Returns a new instance of CsvToXlsx.

Raises:

  • (ArgumentError)


8
9
10
11
# File 'lib/csv_xlsx_converter/converter.rb', line 8

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

Instance Method Details

#convert(output_file) ⇒ Object

Raises:

  • (ArgumentError)


13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/csv_xlsx_converter/converter.rb', line 13

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

  workbook = RubyXL::Workbook.new
  worksheet = workbook[0]

  options = {:encoding => 'bom|UTF-8', :skip_blanks => true}
  CSV.foreach(@input_file, options).each_with_index do |row, row_idx|
    # http://stackoverflow.com/questions/12407035/ruby-csv-get-current-line-row-number
    row.each_with_index do |item, index|
      worksheet.add_cell row_idx, index, item
    end
  end

  workbook.write output_file
end