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

前端 未结 30 2081
鱼传尺愫
鱼传尺愫 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:07

    Though I am late to the game, Graham's answer is far from being optimal. Particularly, you don't have to use the modulo, call ToString() and apply (int) cast. Considering that in most cases in C# world you would start numbering from 0, here is my revision:

    public static string GetColumnName(int index) // zero-based
    {
        const byte BASE = 'Z' - 'A' + 1;
        string name = String.Empty;
    
        do
        {
            name = Convert.ToChar('A' + index % BASE) + name;
            index = index / BASE - 1;
        }
        while (index >= 0);
    
        return name;
    }
    

提交回复
热议问题