rails读取xls上传的文件

时间:2014-01-23 12:51:48

标签: ruby-on-rails xls

我上传了.xls文件,但我无法通过roo阅读。 在控制器中我有:

  def create
    name = params[:upload][:file].original_filename
    directory = "public/uploads"
    path = File.join(directory, name)
    file =  File.open(path, "wb") { |f| f.write(params[:upload][:file].read) }
    flash[:notice] = "File uploaded"
    file.inspect
    Product.import(params[:upload][:file].original_filename)    
    redirect_to upload_path
  end

模特:

  def self.import(file)

  spreadsheet = open_spreadsheet(file)
 end


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

但是上传变量我有String而且我不能使用文件方法。如何打开已上传的文件供roo gem阅读?

1 个答案:

答案 0 :(得分:1)

我在此处描述了如何使用上传而不使用宝石:

https://stackoverflow.com/a/9545030/1001324

您无法使用serveide上的原始文件名。