nelyj / xlsx_to_json

Convert xlsx to json with ruby
15 stars 5 forks source link

how to handle Roo::HeaderRowNotFoundError #4

Open kirykr opened 8 years ago

kirykr commented 8 years ago

ruby excel_to_json.rb excel_file.xlsx /home/kr/.rvm/gems/ruby-2.3.1@ruby231rail5001/gems/roo-2.5.1/lib/roo/base.rb:400:in row_with': Roo::HeaderRowNotFoundError (Roo::HeaderRowNotFoundError) from /home/kr/.rvm/gems/ruby-2.3.1@ruby231rail5001/gems/roo-2.5.1/lib/roo/base.rb:574:inset_headers' from /home/kr/.rvm/gems/ruby-2.3.1@ruby231rail5001/gems/roo-2.5.1/lib/roo/base.rb:469:in search_or_set_header' from /home/kr/.rvm/gems/ruby-2.3.1@ruby231rail5001/gems/roo-2.5.1/lib/roo/base.rb:366:ineach' from excel_to_json.rb:30:in block (2 levels) in <main>' from excel_to_json.rb:23:ineach' from excel_to_json.rb:23:in block in <main>' from excel_to_json.rb:9:ineach' from excel_to_json.rb:9:in `

'

nelyj commented 8 years ago

Hi @kirykr, Can you attach an example from your xlsx ?.

kirykr commented 8 years ago

example file.xlsx

here is my example file.

Thanks,

kirykr commented 7 years ago

Ok here I found the solution. after leaving this quite awhile, i came back and found out that if the sheet.row(1) contains:

[2] pry(main)> attributes
=> {"No"=>"No",
 "Name"=>"Name",
 "Mobile"=>"Mobile",
 "Email (Personal)"=>"Email (Personal)",
 "Email (Rotati)"=>"Email (Rotati)",
 "Date of Birth"=>"Date of Birth",
 nil=>nil}

nil=>nil it will be raised the Roo::HeaderRowNotFoundError (Roo::HeaderRowNotFoundError)

so what I just did is to attributes.compact compact the array to flash out the nil


sheet.each(attributes.compact) do |hash|
      if(!first_row)
        (final_json[sheet_name] ||= []) << hash
      end
      first_row = false
    end
``