Skip to content

Instantly share code, notes, and snippets.

@hikoz
Created November 4, 2011 05:59
Show Gist options
  • Save hikoz/1338754 to your computer and use it in GitHub Desktop.
Save hikoz/1338754 to your computer and use it in GitHub Desktop.
Excel列名変換をPythonで
def col2row(col):
"""
>>> col2row('B')
2
>>> col2row('Z')
26
>>> col2row('AA')
27
>>> col2row('AZ')
52
>>> col2row('BA')
53
>>> col2row('ZZ')
702
>>> col2row('AAA')
703
"""
return sum((ord(c) - 64) * (26 ** i)
for i, c in enumerate(reversed(col)))
def row2col(row):
"""
>>> row2col(2)
'B'
>>> row2col(26)
'Z'
>>> row2col(27)
'AA'
>>> row2col(52)
'AZ'
>>> row2col(53)
'BA'
>>> row2col(702)
'ZZ'
>>> row2col(703)
'AAA'
"""
n = (row - 1) % 26 + 1
c = chr(n + 64)
r = (row - n) / 26
return c if r == 0 else row2col(r) + c
if __name__ == '__main__':
import sys
a = sys.argv
if len(a) == 1:
import doctest
doctest.testmod()
else:
if a[1].isdigit():
print row2col(int(a[1]))
else:
print col2row(a[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment