Created
October 28, 2014 10:07
Read a spreadsheet's fullname column; and split into first and last names
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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