Quick little snippet needed while working on a web app that exports to an Excel worksheet. What I needed was a way to convert column numbers to the lettering that Excel uses. So, for example, column 27 would become AA.
Found a bulk of the solution at Stack Overflow. Logic wasn’t exactly what I was after and I needed it in PHP, but that post got me 99% of the way there.
function colByNumber($colNum) {
$s = '';
$colNum -= 1;
do {
$s = chr(ord('A') + ($colNum % 26)) . $s;
$colNum /= 26;
} while ((int)$colNum-- > 0);
return $s;
}
Only note is that I was using one based indexing in my code, but zero based in this function. Easy enough to just subtract 1 from the column number before starting.
Be First to Comment