We Recommend

The Rails Way The Rails Way
Now, for the first time, there’s a comprehensive, authoritative guide to building production-quality software with Rails. Pioneering Rails developer Obie Fernandez and a team of experts illuminate the entire Rails API, along with the Ruby idioms, design approaches, libraries, and plug-ins that make Rails so valuable.


Posted By

mikegreen on 05/20/08


Tagged

rails ruby web csv excel ror spreadsheet


Versions (?)


Who likes this?

1 person has marked this snippet as a favorite

artmotion


Rails CSV Export


Published in: Rails 


  1. # require 'rubygems' if using this outside of Rails
  2. require 'fastercsv'
  3.  
  4. def dump_csv
  5. @users = User.find(:all, :order => "lastname ASC")
  6. @outfile = "members_" + Time.now.strftime("%m-%d-%Y") + ".csv"
  7.  
  8. csv_data = FasterCSV.generate do |csv|
  9. csv << [
  10. "Last Name",
  11. "First Name",
  12. "Username",
  13. "Email",
  14. "Company",
  15. "Phone",
  16. "Fax",
  17. "Address",
  18. "City",
  19. "State",
  20. "Zip Code"
  21. ]
  22. @users.each do |user|
  23. csv << [
  24. user.lastname,
  25. user.firstname,
  26. user.username,
  27. user.email,
  28. user.company,
  29. user.phone,
  30. user.fax,
  31. user.address + " " + user.cb_addresstwo,
  32. user.city,
  33. user.state,
  34. user.zip
  35. ]
  36. end
  37. end
  38.  
  39. send_data csv_data,
  40. :type => 'text/csv; charset=iso-8859-1; header=present',
  41. :disposition => "attachment; filename=#{@outfile}"
  42.  
  43. flash[:notice] = "Export complete!"
  44. end

Report this snippet 

You need to login to post a comment.