Issue related to import excel file in rails -
i following ryan bates railscast website tutorial importing excel file rails application. , have done it. want perform bit more complex operations excel data. able import whole content of excel file database table. want each row of excel file before inserting database. need perform operations on each row of excel file. don't know how achieve this.
my model name employee , table name employees. model is:-
class employee < activerecord::base def self.import(file) spreadsheet= employee.open_spreadsheet(file) header=spreadsheet.row(1) (2..spreadsheet.last_row).each |i| row=hash[[header,spreadsheet.row(i)].transpose] em=find_by_id(row["id"])||new em.attributes=row.to_hash.slice('firstname') em.save end end def self.open_spreadsheet(file) case file.extname(file.original_filename) #when ".csv" roo::csv.new (file.path nil, :ignore) when ".xlsx" roo::excelx.new (file.path) #when ".xlsx" excelx.new (file.path, nil, :ignore) else raise "unknown file type: #{file.original_filename}" end end end
another problem want pass content of row controller, know in mvc architecture should not pass model data controller. tell me there way out?
don't idolize mvc, more importing data not model-related thing. if care clean mvc - move code rake task.
is background task? if so, don't need controller. otherwise if have user actions on fetched strings, put code controller (e.g, user uploads excel file, inputs data convertation etc).
you (or users) can modify data in iterator. row
hash header key , value ceil content. e.g., if want remove special characters:
def self.import(file) spreadsheet = employee.open_spreadsheet(file) header = spreadsheet.row(1) (2..spreadsheet.last_row).each |data| spreadsheet.row(data).map! |ceil| ceil.class == string ? ceil.gsub!(/[!@%&"]/,'') : ceil } end row = hash[[header,spreadsheet.row(data)].transpose] em = find_by_id(row["id"]) || new em.attributes = row.to_hash.slice('firstname') em.save end end
Comments
Post a Comment