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

标签 ruby spreadsheet-gem

如果我有一个类型为 Spreadsheet::Excel::Worksheetsheet 变量,现在我们可以通过以下方式访问 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"

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

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

我在查看文档时发现 here但找不到我要找的东西。

如果 gem 不允许它,我将如何自己实现它?

最佳答案

这是使用 creek gem 的方法,在解析大型 xlsx 文件时,它比 spreadsheet 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"]

关于ruby - 使用 `spreadsheet` gem 按名称访问单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38234196/

相关文章:

ruby-on-rails - Ruby 电子表格 gem,如何居中对齐数字

ruby - 如何关闭 ruby​​ gem "Spreadsheet?"中的文件

ruby - 如果 block 从不更改累加器,为什么 reduce 不返回初始值?

ruby - Bundler 可以根据我的 ruby​​ 版本(或受其他依赖项限制)自动安装最新版本吗?

ruby - 如何读取列表(列)而不是行中的 cucumber 表

ruby - 排序范围值

ruby - 在 Ruby 中向哈希添加多个项目

ruby - Spreadsheet Gem 在 Ruby 1.9.2 上慢得令人难以忍受