如何在rails中确定csv文件和excel文件的第一行内容

时间:2021-06-29 13:19:58

I have a simple rails app where users need to upload content via csv or Excel. I don't always want to assume that the user knows all the required fields in the database, I just want users to know that first column is required and whatever content placed on the first column enters the mobile_number column in the database. My code sample of what I am talking about is below. I am using the roo gem. It's a simple app so only two database columns are used in the contacts table.

我有一个简单的rails应用,用户需要通过csv或Excel上传内容。我并不总是想假定用户知道数据库中所有必需的字段,我只是想让用户知道第一列是必需的,放在第一列的任何内容都将进入数据库中的mobile_number列。下面是我正在讨论的代码示例。我在用roo宝石。这是一个简单的应用程序,所以联系人表中只使用两个数据库列。

  def load_imported_contacts
    spreadsheet = open_spreadsheet
    header = spreadsheet.row(1)
    (2..spreadsheet.last_row).map do |i|
      row = Hash[[header, spreadsheet.row(i)].transpose]
      contact = Contact.find_by_id(row["id"]) || Contact.new
      contact.name = "content of the second field(optional)"
      contact.mobile_number = "content in the first(required and must be the first column)"
      contact.save!
    end
  end

  def open_spreadsheet
    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

1 个解决方案

#1


2  

After doing some research i finally solved my problem. I should have done this before posting this question. The solution is below

做了一些调查之后,我终于解决了我的问题。在发布这个问题之前,我应该这么做。下面的解决方案是

  def load_imported_contacts
    spreadsheet = open_spreadsheet
    header = spreadsheet.row(1)
    (1..spreadsheet.last_row).map do |i|
      row = Hash[[header, spreadsheet.row(i)].transpose]
      contact = Contact.find_by_id(row["id"]) || Contact.new
      contact.mobile_number = spreadsheet.cell(i,'A')
      contact.name = spreadsheet.cell(i,'B')
      contact
    end
  end

#1


2  

After doing some research i finally solved my problem. I should have done this before posting this question. The solution is below

做了一些调查之后,我终于解决了我的问题。在发布这个问题之前,我应该这么做。下面的解决方案是

  def load_imported_contacts
    spreadsheet = open_spreadsheet
    header = spreadsheet.row(1)
    (1..spreadsheet.last_row).map do |i|
      row = Hash[[header, spreadsheet.row(i)].transpose]
      contact = Contact.find_by_id(row["id"]) || Contact.new
      contact.mobile_number = spreadsheet.cell(i,'A')
      contact.name = spreadsheet.cell(i,'B')
      contact
    end
  end