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

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

    int nCol = 127;
    string sChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    string sCol = "";
    while (nCol >= 26)
    {
        int nChar = nCol % 26;
        nCol = (nCol - nChar) / 26;
        // You could do some trick with using nChar as offset from 'A', but I am lazy to do it right now.
        sCol = sChars[nChar] + sCol;
    }
    sCol = sChars[nCol] + sCol;
    

    Update: Peter's comment is right. That's what I get for writing code in the browser. :-) My solution was not compiling, it was missing the left-most letter and it was building the string in reverse order - all now fixed.

    Bugs aside, the algorithm is basically converting a number from base 10 to base 26.

    Update 2: Joel Coehoorn is right - the code above will return AB for 27. If it was real base 26 number, AA would be equal to A and the next number after Z would be BA.

    int nCol = 127;
    string sChars = "0ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    string sCol = "";
    while (nCol > 26)
    {
        int nChar = nCol % 26;
        if (nChar == 0)
            nChar = 26;
        nCol = (nCol - nChar) / 26;
        sCol = sChars[nChar] + sCol;
    }
    if (nCol != 0)
        sCol = sChars[nCol] + sCol;
    

提交回复
热议问题