Pregunta

I'm using ruby to convert excel files to csv files. Here is the function I have written to do so:

#!/usr/bin/ruby
require 'CSV'
require 'roo'

def xls_to_csv(file,temp_filename)
    if file =~ /\.xlsx$/
        excel = Roo::Excelx.new(file)
    else
        excel = Roo::Excel.new(file)
    end 

    output = File.open(temp_filename, "w")

    1.upto(excel.last_row) do |line|
        output.write CSV.generate_line excel.row(line)
    end 
end

It works fine, except that after any zip codes in the file it will add a ".0". Here is an example of input data:

address state   zip code    name
123 Lane    TX  78705           John Smith
456 Lane    MS  39564           Smohn Jith

And once the .xls file is run through the function, here is the CSV output:

address,state,zip code,name
123 Lane,TX,78705.0,John Smith
456 Lane,MS,39564.0,Smohn Jith

As you can see, the zip codes now have ".0"s after them. Is there anyway to avoid this? Thanks!

¿Fue útil?

Solución

Roo takes the datatype from the Excel cell type. If you control the spreadsheet, I'd suggest you change the cell type to text. Otherwise, you can convert it to a string in your script. For example (please note, I haven't tested this locally so it could be wrong):

1.upto(excel.last_row) do |line|
    data = excel.row(line)
    data[2] = data[2].to_s
    output.write CSV.generate_line data
end
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top