【问题标题】:Ruby Roo Gem - read Excel xlsx sheet into HashRuby Roo Gem - 将 Excel xlsx 表读入哈希
【发布时间】:2018-10-16 09:55:45
【问题描述】:

我卡住了 - 我需要将 Excel 表读入哈希,我决定使用 ROO gem,但我无法理解文档。请看下面:

我得到了 excel 电子表格:

Fruits   Qty   Location
apples   5     Kitchen
pears    10    Bag
plums    15    Backpack

我想把它放入哈希数组中:

myhash =[
{Fruits: "apples", Qty: 5, Location: "Kitchen"},
{Fruits: "pears", Qty: 10, Location: "Bag"},
{Fruits: "plums", Qty: 15, Location: "Backpack"}
}

现在在 roo 文档中我发现了这个:

Use sheet.parse to return an array of rows. Column names can be a String or a Regexp.

sheet.parse(id: /UPC|SKU/, qty: /ATS*\sATP\s*QTY\z/)
# => [{:id => 727880013358, :qty => 12}, ...]

但是当我尝试下面的代码时,我得到一个错误:“ undefined local variable or method `sheet' for main:Object (NameError)”

require 'roo'
workbook = Roo::Spreadsheet.open './fruits.xlsx'
workbook.default_sheet = workbook.sheets.first
sheet.parse(Fruits: "Fruits", Qty: "Qty", Location:"Location", clean:true)

我知道我需要以某种方式定义工作表,但首先我在文档中找不到任何示例。第二:

Almost all methods have an optional argument sheet. If this parameter is omitted, the default_sheet will be used.

我不介意使用任何其他具有更好文档并且可以同时处理 xls 和 xslx 文档的 gem

请帮忙, 提前谢谢你

【问题讨论】:

  • 使用workbook.sheets.first.parse(...)
  • 嗨,不起作用:“Sheet1”的未定义方法“解析”:字符串(NoMethodError)

标签: ruby excel roo-gem


【解决方案1】:

工作表

# Open the workbook
wb = Roo::Spreadsheet.open '/Users/ankur/Desktop/wb.xlsx'
# Get first sheet
sheet = wb.sheet(0)
# Call #parse on that
sheet.parse(Fruits: "Fruits", Qty: "Qty", Location:"Location", clean:true)
#=> [{:Fruits=>"apples", :Qty=>5, :Location=>"Kitchen"}, {:Fruits=>"pearls", :Qty=>10, :Location=>"Bag"}, {:Fruits=>"plums", :Qty=>15, :Location=>"Bagpack"}]

【讨论】:

    【解决方案2】:

    在 Rails 上使用多个 XLSX 电子表格单排序导出数据

    ods.sheets
    
    out_put = ['Info', 'Sheet 2', 'Sheet 3']
    
    ods.each do |sheet|
    
    ods.default_sheet = sheet
    
     ods.each_with_index do |name, sheet|
    
       p sheet.row(1)
     end 
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-07
      • 1970-01-01
      • 1970-01-01
      • 2017-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多