Skip to content
RY

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

Ram Laxman Yadav1 min read

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