将类似excel的列字母转换为整数的最简单方法是什么?
例如:
AB --> 27
AA --> 26
A --> 0
Z --> 25
答案 0 :(得分:8)
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 }
end
或者
def excel_col_index( str )
offset = 'A'.ord - 1
str.chars.inject(0){ |x,c| x*26 + c.ord - offset }
end
答案 1 :(得分:5)
我会做这样的事情:
def column_name_to_number(column_name)
multipliers = ('A'..'Z').to_a
chars = column_name.split('')
chars.inject(-1) { |n, c| multipliers.index(c) + (n + 1) * 26 }
end
答案 2 :(得分:1)
啊没关系..
def cell2num col
val = 0
while col.length > 0
val *= 26
val += (col[0].ord - 'A'.ord + 1)
col = col[1..-1]
end
return val - 1
end
答案 3 :(得分:1)
这是您可以长时间迭代的位之一。我结束了:
"AB1".each_codepoint.reduce(0) do |sum, n|
break sum - 1 if n < 'A'.ord # reached a number
sum * 26 + (n - 'A'.ord + 1)
end # => 27
来自xsv源代码