使用`spreadsheet` gem按名称访问单元格

时间:2016-07-06 21:37:20

标签: ruby spreadsheet-gem

如果我的sheet变量属于Spreadsheet::Excel::Worksheet类型,那么我们现在可以通过以下方式访问B2

MY_CUSTOM_CELL = [1, 1]
sheet[*MY_CUSTOM_CELL] # => Contents of B2

在LibreOffice中(我确定Excel),我可以在“名称框”中为该单元格指定一个名称。看到下图,我给B2命名为“CUSTOM_NAME”。

Giving a cell a custom name using the "Name Box"

不是使用行/列坐标访问该单元格的内容,而是是否可以通过名称访问它?如果单元格改变位置,这将使更容易适应未来的变化。我想做点什么:

sheet.find("CUSTOM_NAME") # => Contents of B2

我查看了here找到的文档,但无法找到我要找的内容。

如果宝石已经不允许,我将如何自己实施?

2 个答案:

答案 0 :(得分:0)

以下是使用 creek gem的方法,它在解析大型xlsx文件时比电子表格 gem快得多。

require 'creek'

workbook = Creek::Book.new some_file.xlsx # Change the file name to suit your needs
worksheet = workbook.sheets[0] # Change the worksheet index to suit your needs. 

# Create hash with cell names (e.g., A1, B5) as keys and cell values as values
cells = Hash.new
  worksheet.rows.each do |row|
    cells.merge!(row)
  end
end

# To access the cell values, just use the corresponding hash keys

# Set value for the A1 cell
cells["A1"] = "foo"

# Print value of C3 cell
puts cells["C3"]

答案 1 :(得分:0)

虽然另一个答案可能是一个不错的选择(我没有亲自未经验证),但这个问题的答案是

Spreadsheet Issue - Feature - Retrieve a cell by its name, not just row and column

目前无法使用电子表格gem来查找名称单元格。

相关问题