Skip to content

Instantly share code, notes, and snippets.

@tonyto
Created August 3, 2012 13:29
Show Gist options
  • Select an option

  • Save tonyto/3247710 to your computer and use it in GitHub Desktop.

Select an option

Save tonyto/3247710 to your computer and use it in GitHub Desktop.
export model object into csv format
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