Fastest function to generate Excel column letters in C#

前端 未结 21 1736
无人共我
无人共我 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:44

    Try this function.

    // Returns name of column for specified 0-based index.
    public static string GetColumnName(int index)
    {
        var name = new char[3]; // Assumes 3-letter column name max.
        int rem = index;
        int div = 17576; // 26 ^ 3
    
        for (int i = 2; i >= 0; i++)
        {
            name[i] = alphabet[rem / div];
            rem %= div;
            div /= 26;
        }
    
        if (index >= 676)
            return new string(name, 3);
        else if (index >= 26)
            return new string(name, 2);
        else
            return new string(name, 1);
    }
    

    Now it shouldn't take up that much memory to pre-generate each column name for every index and store them in a single huge array, so you shouldn't need to look up the name for any column twice.

    If I can think of any further optimisations, I'll add them later, but I believe this function should be pretty quick, and I doubt you even need this sort of speed if you do the pre-generation.

提交回复
热议问题