I have found solution and here are my tips. Hope it can be helpfull for someone faced with the same issue.
1) Route:
resources :leads do
collection { post :export }
end
2) Controller action:
def export
case params[:commit]
when "To Excel" then render xlsx: 'export'
when "To CSV" then send_data @leads.to_csv_modified(@lead_ids), filename: 'export.csv'
else render action: "index"
end
end
3) View:
<%= form_tag export_leads_path, method: :post do %>
<%= text_field_tag :created_at_first %>
<%= text_field_tag :created_at_last%>
<% Lead.new.attributes.keys[0...Lead.new.attributes.keys.length-1].each_with_index do |field, index| %>
<%= check_box_tag "lead_ids[]", field, checked = true %>
<%= field %>
<% end %>
<%= submit_tag 'To Excel', controller: 'leads', action: "export" %>
<%= submit_tag 'To CSV', controller: 'leads', action: "export" %>
<% end %>
4) Axlsx template (invoking in controller with render xlsx: 'export'):
$LOAD_PATH.unshift "#{File.dirname(__FILE__)}/../lib"
require 'axlsx'
p = Axlsx::Package.new
wb = xlsx_package.workbook
style_shout = wb.styles.add_style sz: 16, b: true, alignment: { horizontal: :center }
wb.add_worksheet(name: "#{Time.now.to_date}") do |sheet|
sheet.add_row params[:lead_ids]
@leads.each_with_index do |lead, index|
sheet.add_row params[:lead_ids].map {|e| lead.send(e) }
end
end
5) Method to_csv_modified (invoking in controller with send_data @leads.to_csv_modified(@lead_ids), filename: 'import.csv'):
def self.to_csv_modified(lead_ids, options = {})
CSV.generate(options) do |csv|
csv << lead_ids
all.each do |lead|
csv << lead.attributes.values_at(*lead_ids)
end
end
end
If you would like to see how it is working, visit my github conditional_exporting_to_XLSX_with_params
Another useful links: Axlsx_documentation, Railscast #396 - importing csv-and-excel, Railscast #362 - exporting csv-and-excel