How to solve error: Unquoted fields do not allow or from csv file

Posted by : on

Category : Rails

Hello Friends, We often use csv upload feature in our rails applications. If you have converted a xls or xlsx file to csv, it might be possible that csv file contains \r\n in it. If you are using rubygem roo, it will raise an exception while parsing csv. To import data from csv you have to modify that csv file. Here is an example of that

Replace file content and remove \r\n

  def filter_csv(file_name)
    csv_text = File.read(file_name, :encoding => 'ISO-8859-1')
    #remove blank lines
    csv_text = csv_text.gsub(/(\r\n)/, '')
    @csv = CSV.parse(csv_text, :headers => true, skip_blanks: true)
    # Overwrite csv file
    File.write(file_name, @csv)
    file_name
  end
  @spreadsheet = Roo::CSV.new(filter_csv(file_name))
  # Now you can use this @spreadsheet to manipulate data

Thanks



About Ram Laxman Yadav
Ram Laxman Yadav

Senior Software Engineering Professional | Tech Enthusiast | Mentor | Payments | Hospitality | E-Commerce, based in NCR, India

Email : info@ramlaxman.co.in

Website : https://ramlaxman.co.in