Perl time again. I needed a subroutine to convert an Excel column designation to the corresponding number. For example, I want the subroutine to convert "A" to 1, "B" to 2, "AX" to 50, "ZZ" to 702, etc. Here's a simple subroutine to do so:
- sub ExcelToNum($)
 - {
 - my @xl = split //, uc shift;
 - my $num = 0;
 - foreach (@xl) {
 - $num *= 26;
 - $num += int(ord($_) - 64);
 - }
 - return $num;
 - }
 
Now we should also be able to go the other way around, converting a number to the corresponding Excel column designation, e.g. 50 to "AX", 703 to "AAA", etc.
- sub NumToExcel($)
 - {
 - my $num = int(shift) - 1;
 - my $xl = '';
 - while ($num > 25) {
 - my $rem = $num % 26;
 - $xl .= chr($rem + 65);
 - $num = int($num / 26) - 1;
 - }
 - $xl .= chr($num + 65);
 - return scalar reverse $xl;
 - }
 
No comments:
Post a Comment