How to retrieve date properly using spreadsheet gem in ruby

邮差的信 提交于 2019-12-25 04:15:44

问题


The date column in spreadsheet is formatted as 'mm/dd/yyyy' But when I read the above column via spreadsheet the format is different than the above format.

My code is as follows:

require 'spreadsheet'

Spreadsheet.client_encoding = 'UTF-8'
book = Spreadsheet.open params[:excel_file]
sheet1 = book.worksheet 0
sheet1.each do |row|
  row.set_format 1, Spreadsheet::Format.new(:number_format => 'MM/DD/YYYY')
  h = Hash.new
  h["name"] = row[0]
  h["date"] = row[1]
  ......
end

Currently h["date"] is not retrieving properly. So How should I retrieve the date column properly with my original formatting. Can anyone help me to sort this out !


回答1:


row[1].date or row[1].datetime will get you the right value. I suppose you can set the format while writing it to excel not the other way round.

Update
I thought you just needed your excel date translated as ruby date.
This should do the trick:
excel_date = row[1].date
ruby_date = excel_date.strftime('%m/%d/%Y')



来源:https://stackoverflow.com/questions/11879118/how-to-retrieve-date-properly-using-spreadsheet-gem-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!