Saturday, November 17, 2012

Importing the csv data by browsing and uploading csv from application screen

Importing the csv data by browsing and uploading csv from application screen

Given below code will be placed in view which will allow user to browse file to upload from view. Notice the code
:html => { :multipart => true }
which is mandatory for uploading file.

<% form_for :dump, :url=>{:controller=>"imports", :action=>"csv_import_eqdata2"}, :html => { :multipart => true } do |f| -%>
 <table border=1>
   <tr>
     <td>
      <label for="dump_file">
        Select a EQ Data CSV File2 :
      </label>
     </td>
     <td >
       <%= f.file_field :file -%>
     </td>
   
     <td colspan='2'>
       <%= submit_tag 'Submit' -%>
     </td>
   </tr>
 </table>
<% end -%>

==================
After upload when user will hit submit button, it will call imports controller, csv_import_eqdata2 action. Here are the codes which will be written in controller:

def csv_import_eqdata2 
  @parsed_file=CSV::Reader.parse(params[:dump][:file])
  n=0
     
  @parsed_file.each  do |row|
       
     rsymbol = row[0].strip if !row[0].blank?
     rseries = row[1]
     rtottrdqty = row[2]
     rtottrdval = row[3]

     @eqrawdatas = Eqrawdata.find(:all, :conditions => ["symbol='#{rsymbol}' and series ='#{rseries}' and tottrdqty ='#{rtottrdqty}' and tottrdval ='#{rtottrdval}' and deleted_at is null"])
     
     presentinlotsize = Lotsizedata.find(:first, :conditions =>["symbol='#{rsymbol}' "])

     #Accept only those records whose series is EQ only
     if @eqrawdatas.blank? && !rsymbol.blank? && !rseries.blank? && (rseries == "symbol" or rseries == "EQ") && !presentinlotsize.blank?
     c=Eqrawdata.new
     c.symbol= rsymbol
     c.series=rseries
     c.tottrdqty = rtottrdqty
     c.tottrdval= rtottrdval

     if c.save
        n=n+1
        GC.start if n%50==0
     end
     flash.now[:message]="CSV Import Successful,  #{n} new records added to data base"
     end
     end
   return redirect_to(eqdatalist_url)
end

2 comments:

  1. Thanks for this solution. I was searching for xls based import, and stumbled onto this. I'll be trying this for now.

    ReplyDelete