Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 => 2, AA => 27

like image 783
Jaison Justus Avatar asked Mar 28 '12 10:03

Jaison Justus


People also ask

How do you change columns from letters to numbers in Excel?

In your Excel, click File > Options. In the Excel Options dialog box, select Formulas in the left pane. Under Working with formulas, check the R1C1 reference style box, and click OK.

How do you convert a column of numbers to alphabets?

To change the column headings to letters, select the File tab in the toolbar at the top of the screen and then click on Options at the bottom of the menu. When the Excel Options window appears, click on the Formulas option on the left. Then uncheck the option called "R1C1 reference style" and click on the OK button.


2 Answers

Try:

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]
like image 134
Yoshi Avatar answered Oct 11 '22 20:10

Yoshi


solution 1: best performance and browser compatibility

// 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;
}

solution 2: best performance and compatibility and shorter code (Recommended)

// 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;
}

solution 3: short code (es6 arrow function)

// 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);
}

test:

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

lettersToNumber('AAA'); //703
like image 44
cuixiping Avatar answered Oct 11 '22 20:10

cuixiping