像索引在Excel中的Excel

我已经写了一个函数,将excel像索引(A34)转换成JS索引(数组[0] [33])。

但是当列名更复杂时(例如AA),似乎不起作用。

这是迄今为止的代码

function excel_index(address) { let col = address.charCodeAt(0)-65; let row = address.substring(1)-1; return this[row][col]; } Array.prototype.excel = excel_index; 

你可以使用基数为36的parseInt和一个9的修正(这只得到字母的值)和Array#reduce来创build整个字母数。

26的因子是字母表的长度,更多的左边有一个字母26的位置值。

 function excel_index(address) { var col = address.match(/[AZ]+/)[0], row = address.match(/\d+/i)[0]; return { col: col.split('').reduce((r, a) => r * 26 + parseInt(a, 36) - 9, 0) - 1, row: row - 1 }; } console.log(excel_index('A1')); console.log(excel_index('AA33')); console.log(excel_index('ZZ42'));