Convert a column number into a string

An integer represents the column number of an Excel sheet. Assume that you want to transform the number into a string (title).

Example:

terminal
Column: 1  => A
Column: 27 => AA
Column: 53 => BA

Let's represent the alphabet using an array:

javascript
let alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

Notice that the last letter of an Excel column string always follows the ABCDE...Z sequence.

Use a module function to get it:

javascript
let lastChar = alphabet[(columnNumber - 1) % 26]

If columnNumber is greater than 26, notice that for a complete alphabet iteration, a new letter appears or the previous one increases one position:

terminal
//  1 iteration(s) => A̳A
//  2 iteration(s) => B̳A
//  3 iteration(s) => C̳A
//  4 iteration(s) => D̳A
// ...
// 26 iteration(s) => Z̳A
// 27 iteration(s) => AA̳A
// 28 iteration(s) => AB̳A

The number of iterations points to a letter in the alphabet. Prepend this letter to the title:

javascript
var convertToTitle = function(columnNumber) {
    
    let alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    let lastChar = ''
    let title = ''

    while(columnNumber){

        lastChar = alphabet[(columnNumber - 1) % 26]
        
        // Every 1 complete iteration, there is a new letter or an upgrade of the previous one
        // The number of iterations points to the letter in the alphabet
        //  0 iteration(s) => A  1
        //  1 iteration(s) => AA 27
        //  2 iteration(s) => BA 53
        //  3 iteration(s) => CA 79
        //  4 iteration(s) => DA 105
        // ...
        // 26 iteration(s) => ZA 677
        columnNumber = Math.floor((columnNumber - 1) / 26)
        
        title = lastChar + title
        
    }
    
    return title
    
}

Bonus

And here is the solution the other way round:

javascript
var titleToNumber = function(columnTitle) {
    
    let alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    let lastChar = columnTitle[columnTitle.length - 1]
    let columnNumber = alphabet.indexOf(lastChar) + 1

    for(var i = 1, iterations = 0; i < columnTitle.length; i ++){
        
        lastChar = columnTitle[columnTitle.length - (i + 1)]
        
        // AA   => 1   iteration(s)
        // BA   => 2   iteration(s)
        // AAA  => 27  iteration(s)
        // BAA  => 53  iteration(s)
        // CAA  => 79  iteration(s)
        // ZAA  => 677 iteration(s)
        // AAAA => 703 iteration(s)
        iterations += (alphabet.indexOf(lastChar) + 1) * (26 ** (i - 1)) 
                        
    }
        
    columnNumber += iterations * 26
    
    return columnNumber
    
}

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.