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 =['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                                   
  return redirect_to :back

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

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

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:
  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