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

前端 未结 30 2089
鱼传尺愫
鱼传尺愫 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 00:59

    This is the question all others as well as Google redirect to so I'm posting this here.

    Many of these answers are correct but too cumbersome for simple situations such as when you don't have over 26 columns. If you have any doubt whether you might go into double character columns then ignore this answer, but if you're sure you won't, then you could do it as simple as this in C#:

    public static char ColIndexToLetter(short index)
    {
        if (index < 0 || index > 25) throw new ArgumentException("Index must be between 0 and 25.");
        return (char)('A' + index);
    }
    

    Heck, if you're confident about what you're passing in you could even remove the validation and use this inline:

    (char)('A' + index)
    

    This will be very similar in many languages so you can adapt it as needed.

    Again, only use this if you're 100% sure you won't have more than 26 columns.

提交回复
热议问题