Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert excel column letter to integer in Ruby

Tags:

ruby

excel

What's are the simplest way to convert excel-like column letter to integer?

for example:

AB --> 27
AA --> 26
A --> 0
Z --> 25
like image 855
Kokizzu Avatar asked Nov 06 '14 03:11

Kokizzu


1 Answers

def excel_col_index( str )
  value = Hash[ ('A'..'Z').map.with_index.to_a ]
  str.chars.inject(0){ |x,c| x*26 + value[c] + 1 } - 1
end

Or

def excel_col_index( str )
  offset = 'A'.ord - 1
  str.chars.inject(0){ |x,c| x*26 + c.ord - offset } - 1
end
like image 129
Phrogz Avatar answered Sep 22 '22 02:09

Phrogz