Never been to CodeSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

About this user

Mike

1 total

On This Page:

  1. 1 Rails CSV Export

Rails CSV Export



# require 'rubygems' if using this outside of Rails
require 'fastercsv'

def dump_csv
  @users = User.find(:all, :order => "lastname ASC")
  @outfile = "members_" + Time.now.strftime("%m-%d-%Y") + ".csv"
  
  csv_data = FasterCSV.generate do |csv|
    csv << [
    "Last Name",
    "First Name",
    "Username",
    "Email",
    "Company",
    "Phone",
    "Fax",
    "Address",
    "City",
    "State",
    "Zip Code"
    ]
    @users.each do |user|
      csv << [
      user.lastname,
      user.firstname,
      user.username,
      user.email,
      user.company,
      user.phone,
      user.fax,
      user.address + " " + user.cb_addresstwo,
      user.city,
      user.state,
      user.zip
      ]
    end
  end

  send_data csv_data,
    :type => 'text/csv; charset=iso-8859-1; header=present',
    :disposition => "attachment; filename=#{@outfile}"

  flash[:notice] = "Export complete!"
end
1 total

On This Page:

  1. 1 Rails CSV Export