Skip to content

Instantly share code, notes, and snippets.

@mistrikushal
Last active September 22, 2016 05:45
Show Gist options
  • Save mistrikushal/96d5e40136e121311c323c9a57e0aec2 to your computer and use it in GitHub Desktop.
Save mistrikushal/96d5e40136e121311c323c9a57e0aec2 to your computer and use it in GitHub Desktop.
create csv in ruby on rails
# Create a CSV in Write Mode
CSV.open("#{Rails.public_path}/file_name.csv", 'wb') do |csv|
# Add a first row into CSV which is column names
csv << ['First name', 'Last name', 'Email']
end
# Now we have CSV file created in the public directory of the rails application and also it has columns ready
# Now Let's add some data into it. please note that the data in each cell of the row should be in order with the columns defined.
# Open CSV in Append Mode
CSV.open("#{Rails.public_path}/file_name.csv", 'a+') do |csv|
# Create rows of data
csv << ['John', 'Black', '[email protected]'] # next row after first(columns row)
csv << ['Cory', 'Anderson', '[email protected]'] # another row
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment