简体   繁体   中英

Importing excel file in rails applications

I am following Ryan Bates railcast tutorial for importing excel file through a rail application. My Ruby version is 2.2.4 and rails version is 4.2.6 I installed 'roo' gem already.

My app\\models\\user.rb file is:

class User < ActiveRecord::Base
require 'csv'

def self.import(file)

spreadsheet= open_spreadsheet(file)
header=spreadsheet.row(1)
(2..spreadsheet.last_row).each do |i|
  row=Hash[[header,spreadsheet.row(i)].transpose]
  user=find_by_id(row["id"])||new
  user.attributes=row.to_hash.slice(*accessible_attributes)
  user.save
end
end

def self.open_spreadsheet(file)
case File.extname(file.original_filename)
  #when ".csv" then Roo::Csv.new (file.path nil, :ignore)
  when ".xls" then Roo::Excel.new (file.path)
  #when ".xlsx" then Excelx.new (file.path, nil, :ignore)
  else raise "Unknown file type: #{file.original_filename}"
  end
 end

end

My app\\controllers\\users_controller.rb file is:

class UsersController < ApplicationController
 def index
  @users=User.all
 end
 def import
   User.import(params[:file])
   redirect_to root_url, notice: "Activity data imported!"
 end
end

Now my application home page is working properly. But after selectiong the file from file chooser when I am clicking on the "import excel" button (I have done all this in index.html.erb file),,then it is showing the following error:

RuntimeError in UsersController#import

could not locate a workbook, possibly an empty file passed

Can not solve this problem yet. The method open_spreadsheet is already defined there then whats the reason of the error?

Try changing this line:

spreadsheet= open_spreadsheet(file)

to:

spreadsheet= User.open_spreadsheet(file)

EDIT: You are also missing and end:

def self.import(file)

spreadsheet= open_spreadsheet(file)
header=spreadsheet.row(1)
(2..spreadsheet.last_row).each do |i|
  row=Hash[[header,spreadsheet.row(i)].transpose]
  user=find_by_id(row["id"])||new
  user.attributes=row.to_hash.slice(*accessible_attributes)
  user.save
end
end #<-----------

EDIT:

 class User < ActiveRecord::Base
require 'csv'

def self.import(file)

spreadsheet= open_spreadsheet(file)
header=spreadsheet.row(1)
(2..spreadsheet.last_row).each do |i|
  row=Hash[[header,spreadsheet.row(i)].transpose]
  user=find_by_id(row["id"])||new
  user.attributes=row.to_hash.slice(*accessible_attributes)
  user.save
end
end

def self.open_spreadsheet(file)
case File.extname(file.original_filename)
  #when ".csv" then Roo::Csv.new (file.path nil, :ignore)
  when ".xls" then Roo::Excel.new (file.path)
  #when ".xlsx" then Excelx.new (file.path, nil, :ignore)
  else raise "Unknown file type: #{file.original_filename}"
  end
 end

end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM