Dav*_*ave 15 xls ruby-on-rails roo-gem ruby-on-rails-5
我正在使用Rails 5.我想使用下面的代码解析.xls(不要与.xlsx doc混淆)
book = Roo::Spreadsheet.open(file_location)
sheet = book.sheet(0)
text = sheet.to_csv
csv = CSV.parse(text)
arr_of_arrs = csv
text_content = ""
arr_of_arrs.each do |arr|
arr.map!{|v| v && v.to_f < 1 && v.to_f > 0 ? TimeFormattingHelper.time_as_str(v.to_f * 24 * 3600 * 1000) : v}
text_content = "#{text_content}\n#{arr.join("\t")}"
end
Run Code Online (Sandbox Code Playgroud)
这是我在上面引用的方法
def time_as_str(time_in_ms)
regex = /^(0*:?)*0*/
Time.at(time_in_ms.to_f/1000).utc.strftime("%H:%M:%S.%1N").sub!(regex, '')
end
Run Code Online (Sandbox Code Playgroud)
我遇到麻烦的一个方面是我的.xls doc中出现的单元格
24:08:00
Run Code Online (Sandbox Code Playgroud)
被处理为
1904-01-02T00:08:00+00:00
Run Code Online (Sandbox Code Playgroud)
使用上面的代码.如何解析我在屏幕上看到的值?也就是说,如何将日期值转换为时间值?
作为另一个Excel文档的示例,显示为的单元格
24:02:00
Run Code Online (Sandbox Code Playgroud)
正在被上面的代码解析为
1899-12-31T00:02:00+00:00
Run Code Online (Sandbox Code Playgroud)
您可以使用类似下面的内容并为该字符串编写自定义解析器。
duration = 0
"24:08:01".split(":").each_with_index do |value, i|
if i == 0
duration += value.to_i.hours
elsif i == 1
duration += value.to_i.minutes
else
duration += value.to_i.seconds
end
end
duration.value => 86881 (duration in seconds)
Run Code Online (Sandbox Code Playgroud)
该解析器将采用 的格式hours:minutes:seconds并返回 的实例ActiveSupport::Duration。然后,duration.value会给你秒数。
| 归档时间: |
|
| 查看次数: |
729 次 |
| 最近记录: |