Fast Reports: Exporting to a CSV in Ruby

/ tips-and-tricks / ruby ,  reporting

Need to quickly export a collection as a CSV? Ruby has an awesome class just for this (named CSV of course). With this class you can quickly output a csv string which can then be imported into Excel, Libre Office, etc.

Here's a quick example that is displaying some user information. **Note**: the last line is important for displaying the csv string without the \n character.

users = User.all
headers = ["Name", "Email", "Role"]

csv = CSV.generate do |csv|
  csv << headers # Add the headers to the csv

  users.each do |user|
    csv << [user.name, user.email, user.role]
  end
end

puts csv # output the csv string

Now just copy paste the string from your console into a new spreadsheet and it should properly delineate the columns and data. Easy!

Join the conversation

comments powered by Disqus