Home » excel » How to determine the content of the first row of a csv and excel file using in rails

How to determine the content of the first row of a csv and excel file using in rails

Posted by: admin April 23, 2020 Leave a comment

Questions:

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.

  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
How to&Answers:

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