Skip to content

Instantly share code, notes, and snippets.

@maricris-sn
Created October 28, 2014 10:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maricris-sn/0f1500c504c3314c1d35 to your computer and use it in GitHub Desktop.
Save maricris-sn/0f1500c504c3314c1d35 to your computer and use it in GitHub Desktop.
Read a spreadsheet's fullname column; and split into first and last names
# Assumes gem install 'roo' has been done
require 'roo'
# Spreadsheet filename I want to read
file_path = ENV["CONTACT_PATH"]
puts "Importing data from " + file_path
# Opening the file using roo
spreadsheet = case File.extname(file_path)
when ".xls" then Roo::Excel.new(file_path, {})
when ".xlsx" then Roo::Excelx.new(file_path, {})
else puts "Unknown File Type for import!"
end
# get the header
header = spreadsheet.row(1).compact.collect{|x| x.parameterize(sep='_').downcase}
# creating a csv file with broken down full names
CSV.open("#{file_path.split(File.extname(file_path)).first}.csv", "w") do |csv|
csv << header.flatten
# iterate on your spreadsheet data
(2..spreadsheet.last_row).each do |i|
attributes = Hash[[header, spreadsheet.row(i)].transpose]
fullname = attributes["full_name"]
puts "#{fullname}"
fullname_array = fullname.split(' ')
# assumes that only the last item is the last name
attributes["first_name"] = (fullname_array - [fullname_array[-1]]).join(' ')
attributes["last_name"] = fullname_array[-1]
row = []
header.each do |h|
row << attributes[h]
end
csv << row
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment