Created
August 3, 2012 13:29
-
-
Save tonyto/3247710 to your computer and use it in GitHub Desktop.
export model object into csv format
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def export_as_csv | |
| model = MyModel.all | |
| filename = params[:action] + ".csv" | |
| if request.env['HTTP_USER_AGENT'] =~ /msie/i | |
| headers['Pragma'] = 'public' | |
| headers["Content-type"] = "text/plain" | |
| headers['Cache-Control'] = 'no-cache, must-revalidate, post-check=0, pre-check=0' | |
| headers['Content-Disposition'] = "attachment; filename=\"#{filename}\"" | |
| headers['Expires'] = "0" | |
| else | |
| headers["Content-Type"] ||= 'text/csv' | |
| headers["Content-Disposition"] = "attachment; filename=\"#{filename}\"" | |
| headers["Content-Transfer-Encoding"] = "binary" | |
| end | |
| csv_string = CSV.generate do |csv| | |
| csv << ["name", "age", "gender"] | |
| model.each do |i| | |
| csv << [i["name"],i["age"],i["gender"]] | |
| end | |
| end | |
| render :text => csv_string | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment