Fastest function to generate Excel column letters in C#

前端 未结 21 1747
无人共我
无人共我 2020-11-29 02:30

What is the fastest c# function that takes and int and returns a string containing a letter or letters for use in an Excel function? For example, 1 returns \"A\", 26 return

21条回答
  •  春和景丽
    2020-11-29 02:50

    The code I'm providing is NOT C# (instead is python) but the logic can be used for any language.

    Most of previous answers are correct. Here is one more way of converting column number to excel columns. solution is rather simple if we think about this as a base conversion. Simply, convert the column number to base 26 since there is 26 letters only. Here is how you can do this:

    steps:

    • set the column as a quotient

    • subtract one from quotient variable (from previous step) because we need to end up on ascii table with 97 being a.

    • divide by 26 and get the remainder.

    • add +97 to remainder and convert to char (since 97 is "a" in ASCII table)
    • quotient becomes the new quotient/ 26 (since we might go over 26 column)
    • continue to do this until quotient is greater than 0 and then return the result

    here is the code that does this :)

    def convert_num_to_column(column_num):
        result = ""
        quotient = column_num
        remainder = 0
        while (quotient >0):
            quotient = quotient -1
            remainder = quotient%26
            result = chr(int(remainder)+97)+result
            quotient = int(quotient/26)
        return result
    
    print("--",convert_num_to_column(1).upper())
    

提交回复
热议问题