Search code examples
ruby-on-railsrubycsvfastercsv

Ruby csv import trouble


I tried to import data from csv in my rails app, but something went wrong:

CSV::MalformedCSVError in ArticlesController#index
Unclosed quoted field on line 1.

My csv looks like this:

"Код";"№ по каталогу  (артикул)";"Наименование  товара";"Ед. изм.";"Цена опт.";"Доп.";"Остатки";"Класс";"Группа";"Бренд";"Блок."
2223;15-562-44;15-562-44 (27-B07-F) VW Polo 95-R                                                                   ;шт  ;37,430;;;Амортизаторы                                                                                        ;Амортизаторы BOGE                                                                                   ;; 
10327;24-052-1;24-052-1(46-A27-0) LAND ROVER 84- F                                                                 ;шт  ;68,750;;;Амортизаторы                                                                                        ;Амортизаторы BOGE                                                                                   ;; 
10328;24-053-1;24-053-1(46-A28-0) LAND ROVER 84- R                                                                 ;шт  ;68,750;;;Амортизаторы                                                                                        ;Амортизаторы BOGE                                                                                   ;; 

Maybe this is because of the first line (which has no ;;)

My code look like this:

def csv_import 
    require 'csv'
    file = File.open("/#{Rails.public_path}/uploads/smallcsv.csv")
    #csv = CSV.parse(file)


    csv = CSV.open(file, "r:ISO-8859-15:UTF-8", {:col_sep => ";", :row_sep => ";;", :headers => :first_row})
    file_path = "/#{Rails.public_path}/uploads/smallcsv.csv"
    #@parsed_file=CSV::Reader.parse(file_path)

    csv.each do |row| 
      ename = row[2]
      eprice = row[5]
      eqnt = row[7]
      esupp = row[10]

      logger.warn(ename)
    end

  end

I'm running ruby 1.9+ with fastercsv gem


Solution

  • I figured this out myself using "CSV - Unquoted fields do not allow \r or \n (line 2)".

    The problem was with the first line, so :auto helped me.