Saturday, February 4, 2012

Export csv at a particular pre-defined folder in rails application

Export excel from Rails application - User gets a link on view and when user clicks on that link user is not asked about the location for saving the csv, csv is exported and saved at pre-defined location. In this case, you cannot create excel view.
Saving the csv at a particular pre-defined folder
Code snippets:

1. Add action on 'eqrawdatas' controller: 
def export_list
  require 'csv'
  symboldetails = Masterdata.find(:all)
  config = read_config_exp  

    outfile = File.open(File.join(config['event_export_path'],"export_data.csv"), "w")
      CSV::Writer.generate(outfile) do |csv|
      csv << Array["Uniq Symbol", "Symbol", "Data Date" ]
      symboldetails.each do |symboldetail|
        arr = []
    arr = Array[symboldetail.uniqsymbol, symboldetail.symbol, symboldetail.data_date.strftime("%b %d, %Y")  ]
        csv << arr                                   
      end
    end
    outfile.close 
  return redirect_to :back
end

2. In the same controller, add a private method
  private
  #read the config file

  def read_config_exp
    config_file = File.open("#{RAILS_ROOT}/misc/export_event.yml")
    erb = ERB.new(config_file.read)
    all_configs = YAML.load(erb.result(binding))
    dir = all_configs["All"]["event_export_path"]
    Dir.mkdir(dir) unless File.exists?(dir)
    all_configs['All']
  end

3. Create export_event.yml file in misc folder inside rails application
In rails application misc folder, create export_event.yml file. In this file it will export the csv data in C:\exported_csv folder:
All:
  event_export_path: C:\exported_csv

4. Add link on view:
<%= link_to("Export EQ Date Data List", :controller => :eqrawdatas, :action => :export_list) %>
 

No comments:

Post a Comment