Ruby script to read the last filled cell in a column

你说的曾经没有我的故事 提交于 2019-12-12 17:26:38

问题


i need a ruby code to read the column a and find where does the last filled cell in the column ends.In the image uploaded the last filled data is i in cell "A21". i need to know this cell address through ruby code.


回答1:


I would do using the Ruby stdlib WIN32OLE .

require 'win32ole'

# create an instance of the Excel application object
excel = WIN32OLE.new('Excel.Application')
# make Excel visible
excel.visible = true
# open the excel from the desired path
wb=excel.workbooks.open("C:\\Users\\test.xlsx")
# get the first Worksheet
wbs= wb.Worksheets(1)
# value of the constants I picked up from 
# http://techsupt.winbatch.com/ts/T000001033005F9.html
rng = wbs.range("1:1").SpecialCells(11) # value of 'xlCellTypeLastCell' is 11
rng.value # => "i"
rng.address # => "$A$21"
# to get the row and column number
row,col = rng.row,rng.column
[row,col] # => [21,1]

Look at the MSDN documentation of SpecialCells.

You can get the value of xlCellTypeLastCell from the version of MSExcel installed in your pc. Just do ALT+F11 -> F2 -> search the constant there :




回答2:


try using 'spreadsheet' gem

book = Spreadsheet.open 'myexcel.xls';
sheet1 = book.worksheet 0
last_value = nil
sheet1.each do |row|
  last_value = row[0].present? && row[0]
end
last_value
=>
"i"


来源:https://stackoverflow.com/questions/22190877/ruby-script-to-read-the-last-filled-cell-in-a-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!