Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Active Admin Exporting to CSV file

I'm using active admin to use admin functionalities in my Rails 4.0 application. I have a users table that lists

  • id
  • name
  • email
  • phone no

I have also put a button on the top of the list like this.

action_item only: :index do
  link_to 'Export to CSV', '#'
end

I want to export the users id name & email into a csv file when I click on this button. Please help me to do this

like image 841
Nidhin S G Avatar asked Jun 26 '15 09:06

Nidhin S G


2 Answers

Just add section inside admin

csv do
  column :id
  column :name
  column :email
end

Check also active admin customize CSV

If you open link, you will see line

column(:author) { |post| post.author.full_name }

It adds authors name into the post csv file, his way you can add any field you want

like image 75
Nermin Avatar answered Oct 02 '22 06:10

Nermin


The code below is working:

collection_action :import_csv, method: :get do
  users = User.all.order("id ASC")
  csv = CSV.generate( encoding: 'Windows-1251' ) do |csv|
    csv << [ "Id", "Name", "Gender", "Email", "Mobile number","Email Verified",
    "Mobile Verified", "Language Preference", "Counselling Preference", "Job Role Name",
    "Liked", "Disliked", "Favourited", "Shared", "Video Watched"]
    users.each do |u|
      email_verified = u.is_email_verified ? "Yes" : "No"
      mobile_verified = u.is_mobile_verified ? "Yes" : "No"
      counselling_preference = u.counselling_preference ? "Yes" : "No"
      userarry = [ u.id, u.name, u.gender, u.email, u.mobile_number,  email_verified,
      mobile_verified, u.language_preference, counselling_preference]
      csv << userarry + ["", "","","", "", ""]
    end
  end

  send_data csv.encode('Windows-1251'), type: 'text/csv; charset=windows-1251; header=present', disposition: "attachment; filename=accounting_report.csv"
end

action_item :add do
  link_to "Export to CSV", import_csv_admin_users_path, method: :get
end
like image 39
user1415139 Avatar answered Oct 02 '22 06:10

user1415139