将excel列字母表(例如AA)转换为数字(例如25)

时间:2012-03-28 10:23:08

标签: javascript

在我的网格中,列标题名为A,B,C...,AA,AB,AC,...等,就像excel电子表格一样。如何将字符串转换为数字:A => 1, B => 2, AA => 27

8 个答案:

答案 0 :(得分:38)

尝试:

var foo = function(val) {
  var base = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', i, j, result = 0;

  for (i = 0, j = val.length - 1; i < val.length; i += 1, j -= 1) {
    result += Math.pow(base.length, j) * (base.indexOf(val[i]) + 1);
  }

  return result;
};

console.log(['A', 'AA', 'AB', 'ZZ'].map(foo)); // [1, 27, 28, 702]

答案 1 :(得分:7)

以下是您应该实施的代码的快速示例。 这适用于任何给定数量的字母。

function letterToNumbers(string) {
    string = string.toUpperCase();
    var letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', sum = 0, i;
    for (i = 0; i < string.length; i++) {
        sum += Math.pow(letters.length, i) * (letters.indexOf(string.substr(((i + 1) * -1), 1)) + 1);
    }
    return sum;
}

答案 2 :(得分:7)

解决方案1:最佳性能和浏览器兼容性

// convert A to 1, Z to 26, AA to 27
function lettersToNumber(letters){
    var chrs = ' ABCDEFGHIJKLMNOPQRSTUVWXYZ', mode = chrs.length - 1, number = 0;
    for(var p = 0; p < letters.length; p++){
        number = number * mode + chrs.indexOf(letters[p]);
    }
    return number;
}

解决方案2:最佳性能和兼容性以及更短的代码(推荐)

// convert A to 1, Z to 26, AA to 27
function lettersToNumber(letters){
    for(var p = 0, n = 0; p < letters.length; p++){
        n = letters[p].charCodeAt() - 64 + n * 26;
    }
    return n;
}

解决方案3:短代码(es6箭头功能)

// convert A to 1, Z to 26, AA to 27
function lettersToNumber(letters){
    return letters.split('').reduce((r, a) => r * 26 + parseInt(a, 36) - 9, 0);
}

试验:

['A', 'Z', 'AA', 'AB', 'ZZ','BKTXHSOGHKKE'].map(lettersToNumber);
// [1, 26, 27, 28, 702, 9007199254740991]

lettersToNumber('AAA'); //703

答案 3 :(得分:2)

我刚写了一个垃圾场f @#$ snippet ...需要优化.. :)

charToNum = function(alpha) {
        var index = 0
        for(var i = 0, j = 1; i < j; i++, j++)  {
            if(alpha == numToChar(i))   {
                index = i;
                j = i;
            }
        }
        console.log(index);
    }

numToChar = function(number)    {
        var numeric = (number - 1) % 26;
        var letter = chr(65 + numeric);
        var number2 = parseInt((number - 1) / 26);
        if (number2 > 0) {
            return numToChar(number2) + letter;
        } else {
            return letter;
        }
    }
chr = function (codePt) {
        if (codePt > 0xFFFF) { 
            codePt -= 0x10000;
            return String.fromCharCode(0xD800 + (codePt >> 10), 0xDC00 + (codePt & 0x3FF));
        }
        return String.fromCharCode(codePt);
    }

charToNum('A')=&gt;返回1并且charToNum('AA')=&gt;返回27;

答案 4 :(得分:1)

我用更详细的形式重新编写了Yoshi's answer,更好地解释了它是如何工作的,并且更容易移植到其他语言:

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]

答案 5 :(得分:0)

Public Function ColLet2Num(Letras As String)
'RALONSO MAYO 2017
'A-> 1
'OQ ->407
'XFD->16384
Dim UnChar As String
Dim NAsc As Long
Dim F As Long
Dim Acum As Long
Dim Indice As Long
Letras = UCase(Letras)
Acum = 0
Indice = 0
For F = Len(Letras) - 1 To 0 Step -1

    UnChar = Mid(Letras, F + 1, 1)
    NAsc = Asc(UnChar) - 64
    Acum = Acum + (NAsc * (26 ^ Indice))
    Indice = Indice + 1
Next
If Acum > 16384 Then
    MsgBox "La celda máxima es la XFD->16384", vbCritical
End If
ColLet2Num = Acum
End Function

答案 6 :(得分:0)

// Given Column to Number
function colToNumber(str) {
  var num = 0
  var i = 0
  while (i < str.length ) {
    num = str[i].charCodeAt() - 64 + num * 26;
    i++; 
  }
  return num;
}

//Given Number to Column name
function numberToCol(num) {
  var str = '', q, r;    
  while (num > 0) {
    q = (num-1) / 26;
    r = (num-1) % 26
    num = Math.floor(a) 
    str = String.fromCharCode(65 + r) + str;
  }
  return str;
}

答案 7 :(得分:0)

    const getColumnName = (columnNumber) => {
        let columnName = "";
        const alphabets = "abcdefghijklmnopqrstuvwxyz".toUpperCase();
        while (columnNumber > 0) {
            const rem = columnNumber % 26;
            if (rem === 0) {
                columnName += "Z";
                columnNumber = columnNumber / 26 - 1;
            } else {
                columnName += alphabets[rem - 1];
                columnNumber = Math.floor(columnNumber / 26);
            }
        }
        return columnName.split("").reverse().join("");
    };

    console.log(getColumnName(27));