Skip to content

Instantly share code, notes, and snippets.

@francois-blanchard
Last active January 27, 2016 13:00
Show Gist options
  • Save francois-blanchard/fce59c3df44752457639 to your computer and use it in GitHub Desktop.
Save francois-blanchard/fce59c3df44752457639 to your computer and use it in GitHub Desktop.
Excel to csv (gem roo)

Excel to csv (gem roo)

documentation

class ExcelToCsv
  attr_accessor :input_path, :output_path, :col_sep

  def initialize(input_path:, output_path:, col_sep: ';')
    @input_path = input_path
    @output_path = output_path
    @col_sep = col_sep
    @extension = extension
  end

  def process
    sheet = Roo::Spreadsheet.open(@input_path, extension: symbole_extension)
    csv_content = CSV.parse(sheet.to_csv(nil, ';'), col_sep: @col_sep)
    create_csv(csv_content)
  end

  private

  def create_csv(csv_content)
    CSV.open(@output_path, 'w', headers: true, col_sep: @col_sep) do |csv|
      csv_content.each do |row|
        csv << row
      end
    end
  end

  def extension
    File.extname(@input_path)
  end

  def symbole_extension
    @extension[1..-1].to_sym
  end
end

Xls support

gem roo-xls

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment