Rails CSV Export


/ Published in: Rails



Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.