mgtemp
mgtemp

Reputation: 248

Get null values in Ruby Spreadsheet gem

I'm trying to take an excel file and put it into Postgres. I can access the file and read rows from it.

require 'spreadsheet'
Spreadsheet.client_encoding = 'UTF-8'
book = Spreadsheet.open 'C:\test\RubyTestFile.xls'
sheet1 = book.worksheet 0
$test_array = []
sheet1.each do |row|
    $test_array += row
end
print $test_array

My problem is that it won't read null values. Is there a method to grab say 3 columns of every row? Should I handle this when I upload to postgres instead? Is there a better way of doing this? I tried searching but couldn't find anything.

Upvotes: 0

Views: 476

Answers (1)

tadman
tadman

Reputation: 211670

Here's a slightly more Ruby interpretation:

require 'spreadsheet'

Spreadsheet.client_encoding = 'UTF-8'

def read_spreadsheet(path)
  book = Spreadsheet.open(path)
  sheet1 = book.worksheet 0

  test_array = [ ]

  sheet1.each do |row|
    test_array << (row + [ nil ] * 3).first(3)
  end

  test_array
end

puts read_spreadsheet('C:\test\RubyTestFile.xls').inspect

If you'd rather have literal 'null' in there, you can substitute that for the nil in the array there.

Upvotes: 1

Related Questions