Once I had a requirement to create a function in PHP that could convert a numerical column index into its corresponding Excel column name. Fortunately, I found a unique approach in the PHP documentation that utilized modulo of powers of 26. I successfully adapted this function to JavaScript, making it versatile and efficient:
function convertNumToAlpha($num) {
let $result = '', $index, $num;
for ($index = 1; $num >= 0 && $index < 10; $index++) {
$result = String.fromCharCode(65 + ($num % Math.pow(26, $index) / Math.pow(26, $index - 1))) + $result;
$num -= Math.pow(26, $index);
}
return $result;
}
See the original source
Usage examples:
convertNumToAlpha(0); //A
convertNumToAlpha(27); //AB
convertNumToAlpha(1023); //AMJ
Furthermore...
let columns=[];
for(let i=0; i<=1023; i++) {
columns.push(convertNumToAlpha(i));
}
//["A","B","C",..."AA","AB",..."AMJ"]
For a more concise version:
let columns=[...Array(1024).keys()].map(convertNumToAlpha)