Ruby script to read the last filled cell in a colu

2019-07-19 17:17发布

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. enter image description here

2条回答
够拽才男人
2楼-- · 2019-07-19 17:49

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"
查看更多
兄弟一词,经得起流年.
3楼-- · 2019-07-19 18:04

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 :

constant value

查看更多
登录 后发表回答