如果我有一个类型为 Spreadsheet::Excel::Worksheet
的 sheet
变量,现在我们可以通过以下方式访问 B2
:
MY_CUSTOM_CELL = [1, 1]
sheet[*MY_CUSTOM_CELL] # => Contents of B2
在 LibreOffice(我确定是 Excel)中,我可以在“名称框”中为该单元格指定一个名称。请参见下图,我已将 B2 命名为“CUSTOM_NAME”。
不是使用行/列坐标访问该单元格的内容,是否可以通过名称访问它?如果单元改变位置,这将使它更容易适应 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/