【问题标题】:Error while importing .xlsx file using roo gem in ruby on rails在 ruby​​ on rails 中使用 roo gem 导入 .xlsx 文件时出错
【发布时间】:2016-01-25 18:40:42
【问题描述】:

我收到以下错误:

NoMethodError in ClientsController#table
undefined method `phone' for nil:NilClass

当我尝试将 .xlsx、.xls 或 .csv 文件导入 ruby​​ on rails 应用程序时会发生这种情况。

型号代码如下:

attr_accessible :name, :kind, :address_attributes, :emails_attributes, :phones_attributes, :attachments_attributes

  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]
      client = find_by_id(row["id"]) || new
      client.attributes = row.to_hash.slice(*accessible_attributes)
      client.save!
    end
  end

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

控制器代码如下:

  def import
    Client.import(params[:file])
    redirect_to clients_path, notice: "Clients imported."
  end

apps/Services/config/application.rb 文件包含以下代码:

require 'csv'
require 'iconv'

gem 文件包括以下内容:

gem 'roo', '~> 2.1.0'
gem "iconv", "~> 1.0.3"
gem 'roo-xls'

【问题讨论】:

    标签: ruby-on-rails ruby excel


    【解决方案1】:

    我认为您应该为 Roo gem 使用这种语法:

    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, nil, :ignore)
      when ".xlsx" then Roo::Excelx.new(file.path, nil, :ignore)
      else 
        raise "Unknown file type: #{file.original_filename}"
      end
    end
    

    【讨论】:

    • 我采纳了你的建议@marwen。它不起作用:ClientsController#import 中的 RuntimeError 未知文件类型:client1.xls
    • 您是否使用carrier_wave 进行文件上传?
    • 是的,我正在使用carrier_wave进行文件上传
    • 我应用了您的修改。它不起作用,出现以下错误:undefined method `file' for #<:http::uploadedfile:0x00555aec003b78>
    • 这说明你没有在这里使用carrier_wave。我们很好地恢复到您以前的代码并对其进行更多调查。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-10
    • 2011-06-06
    • 2017-06-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多