Convert excel column alphabet (e.g. AA) to number (e.g., 25)

后端 未结 7 1772
余生分开走
余生分开走 2020-12-13 10:55

In my grid the column headers are named A,B,C...,AA,AB,AC,...etc like an excel spreadsheet. How can I convert the string to number like: A => 1, B =>

7条回答
  •  时光说笑
    2020-12-13 11:20

    I rewrote Yoshi's answer in a more verbose form that explains better how it works and is easier to port to other languages:

    var foo = function(val) {
        var base = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        var baseNumber = base.length;
    
        var runningTotal = 0;
        var characterIndex = 0;
        var indexExponent = val.length - 1;
    
        while( characterIndex < val.length ){
            var digit = val[characterIndex];
            var digitValue = base.indexOf(digit) + 1;
            runningTotal += Math.pow(baseNumber, indexExponent) * digitValue;
    
            characterIndex += 1
            indexExponent -= 1
        }
    
        return runningTotal;
    };
    
    console.log(['A', 'AA', 'AB', 'ZZ'].map(foo)); // [1, 27, 28, 702]
    

提交回复
热议问题