Monday, May 9, 2016

Converting Excel Column Designation to Number

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:
  1. sub ExcelToNum($)  
  2. {  
  3.     my @xl = split //, uc shift;  
  4.     my $num = 0;  
  5.     foreach (@xl) {  
  6.         $num *= 26;  
  7.         $num += int(ord($_) - 64);  
  8.     }  
  9.     return $num;  
  10. }  

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.
  1. sub NumToExcel($)  
  2. {  
  3.     my $num = int(shift) - 1;  
  4.     my $xl = '';  
  5.     while ($num > 25) {  
  6.         my $rem = $num % 26;  
  7.         $xl .= chr($rem + 65);  
  8.         $num = int($num / 26) - 1;  
  9.     }  
  10.     $xl .= chr($num + 65);  
  11.     return scalar reverse $xl;  
  12. }  

No comments:

Post a Comment