Fastest function to generate Excel column letters in C#

前端 未结 21 1779
无人共我
无人共我 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 03:04

    @Neil N -- nice code I think the thirdLetter should have a +64 rather than +65 ? am I right?

    public string Letter(int intCol) {
    
        int intFirstLetter = ((intCol) / 676) + 64;
        int intSecondLetter = ((intCol % 676) / 26) + 64;
        int intThirdLetter = (intCol % 26) + 65;  ' SHOULD BE + 64?
    
        char FirstLetter = (intFirstLetter > 64) ? (char)intFirstLetter : ' ';
        char SecondLetter = (intSecondLetter > 64) ? (char)intSecondLetter : ' ';
        char ThirdLetter = (char)intThirdLetter;
    
        return string.Concat(FirstLetter, SecondLetter, ThirdLetter).Trim();
    }
    

提交回复
热议问题