Skip to content

Instantly share code, notes, and snippets.

@oinariman
Last active August 17, 2016 06:39
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save oinariman/eca97eb195740aeca65e to your computer and use it in GitHub Desktop.
Save oinariman/eca97eb195740aeca65e to your computer and use it in GitHub Desktop.
Convert Excel to JSON
require 'spreadsheet'
require 'json'
Spreadsheet.client_encoding = 'UTF-8'
begin
book = Spreadsheet.open $*[0]
rescue
STDERR.puts "usage: ruby x2j.rb excel_file"
exit false
end
book.worksheets.each do |sheet|
next if sheet.name.index('!') == 0
labels = sheet.rows.first
rows = []
sheet.rows[1..-1].each do |row|
hash = Hash.new()
row.each_with_index do |cell, i|
hash[labels[i]] = cell.kind_of?(String) && cell.include?(',') ? cell.split(',') : cell
end
rows.push hash
end
f = File.open(sheet.name + '.json', 'w')
f.write JSON.generate(rows)
f.close
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment