How to convert a column number (e.g. 127) into an Excel column (e.g. AA)

前端 未结 30 2664
鱼传尺愫
鱼传尺愫 2020-11-22 00:35

How do you convert a numerical number to an Excel column name in C# without using automation getting the value directly from Excel.

Excel 2007 has a possible range o

30条回答
  •  执笔经年
    2020-11-22 01:08

    Sorry, this is Python instead of C#, but at least the results are correct:

    def excel_column_number_to_name(column_number):
        output = ""
        index = column_number-1
        while index >= 0:
            character = chr((index%26)+ord('A'))
            output = output + character
            index = index/26 - 1
    
        return output[::-1]
    
    
    for i in xrange(1, 1024):
        print "%4d : %s" % (i, excel_column_number_to_name(i))
    

    Passed these test cases:

    • Column Number: 494286 => ABCDZ
    • Column Number: 27 => AA
    • Column Number: 52 => AZ

提交回复
热议问题