How to keep value type in Nokogiri?

178 views Asked by At

I have a method that is parsing through a spreadsheet row by row. I also am parsing the rows for each cells value. I can get the string version of the values by using

row.xpath("Cell").each do |cell|
    row_array << cell.text
end

I know that my problem is that I am using text, but is there a value method? I tried searching, but I couldn't find anything. I need the values in order to upload this to Postgres.

I need the array to be able to have ["string", double, date] so I can't just change the format of all of them.

Here is an example of two cells.

<Cell><Data ss:Type="String"></Data></Cell>
<Cell ss:StyleID="s_decimal7RPT"><Data ss:Type="Number">6.7445747E5</Data></Cell>
1

There are 1 answers

0
mgtemp On
 f = File.open(path)
 doc = Nokogiri::XML(f)
 doc.remove_namespaces!
 doc.xpath("//Worksheet/Table/Row").each do |row|
    row_array = [ ]
    row.css("Cell").each do |cell|
        if(cell.css("Data").attr("Type").to_s == 'String')
        row_array << cell.text
    elsif(cell.css("Data").attr("Type").to_s == 'Number')
        row_array << cell.text.to_f
    elsif(cell.css("Data").attr("Type").to_s == 'DateTime')
        row_array << Date.parse(cell.text).strftime("%Y-%m-%d")
    end
end
row_array.collect! {|element| element = (element.presence || nil)}
print row_array
puts
puts    
end
f.close

Just in case someone else needs it.