Skip to main content

adding-export-to-csv-function

Adding "EXPORT TO CSV" function​

Here is a little developer manual, for those who wants to add "EXPORT TO CSV" function into WebPage:

1 Get link to page that you want to export to CSV

Example of web page: https://www.powr.io/admin/cancel-feedback

2 You want to add link to the page when data is ready to be exported

Corresponding template for our web page is /app/views/admin/cancel_feedback.html.haml

  • add following line (tab should be placed where appropriate):

.panel.panel-default

.panel-heading

.row

.col-sm-12%

h2 Stats

.col-sm-12

%h4

- if @app_cancel_data.present? || @pro_cancel_data.present? || @enterprise_cancel_data.present?

= link_to 'Export to excel', start_date:@start_date,end_date:@end_date, format: 'csv', method: :get

Clarification:

The first condition makes sure that our link to CSV file is available if only we have data to export

And if data is available we will send it to our CSV.erb script

3 Next you want to "draw" your csv file:

  • create a new file at /app/views/admin/cancel_feedback.csv.erb
  • add following lines:

//adding header to CSV file

<% headers = ['Email', 'Type', 'Reason', 'App', 'Platform', 'Apps','Date'] %>

//generating CSV file

<%= CSV.generate_line(headers).strip.html_safe %>

// looping data and adding them into file

<% @app_cancel_data.each do |data| %>

<% apps = [data[:user_email], data[:display_reason], data[:details], data[:app_type], data[:external_id_type], data[:app_count], data[:created_at]] %>

<%= CSV.generate_line(apps).strip.html_safe %>

<% end %>

Data is already used at /app/controllers/admin_controller.rb in "def cancel_feedback" function, so in csv.erb file we can just call it. And data is actually collected at /lib/admin_analytics.rb.

That is all folks 💯

Made with <3 by Aigul!