http://qs1969.pair.com?node_id=11114715


in reply to Get Excel column name for given decimal number

Incrementing the column name auto-magically rolls 'Z' over to 'AA' and 'ZZ' over to 'AAA' so could be used here if access to non-core modules is difficult.

johngg@shiraz:~/perl/Monks$ perl -Mstrict -Mwarnings -E ' my @tests = ( -3, 0, 1, 26, 27, 701, 702, 703, 10342, 397645 ); foreach my $test ( @tests ) { printf qq{Col. no. %6d : Col name %s\n}, $test, getColName( $test +); } sub getColName { my $colNo = shift; return q{Bad column number} unless $colNo > 0; my $colName = q{A}; return $colName if $colNo == 1; do { $colName ++; $colNo -- } while $colNo > 1; return $colName; }' Col. no. -3 : Col name Bad column number Col. no. 0 : Col name Bad column number Col. no. 1 : Col name A Col. no. 26 : Col name Z Col. no. 27 : Col name AA Col. no. 701 : Col name ZY Col. no. 702 : Col name ZZ Col. no. 703 : Col name AAA Col. no. 10342 : Col name OGT Col. no. 397645 : Col name VPFA

I hope this is of interest.

Update : The do { ... } while ... ; using a statement modifier always executes at least once, thus making the return $colName if $colNo == 1; statement ahead of it necessary. Using while ( ... ) { ... } works better here.

johngg@shiraz:~/perl/Monks$ perl -Mstrict -Mwarnings -E ' my @tests = ( -3, 0, 1, 26, 27, 701, 702, 703, 10342, 397645 ); foreach my $test ( @tests ) { printf qq{Col. no. %6d : Col name %s\n}, $test, getColName( $test +); } sub getColName { my $colNo = shift; return q{Bad column number} unless $colNo > 0; my $colName = q{A}; while ( $colNo > 1 ) { $colName ++; $colNo --; } return $colName; }' Col. no. -3 : Col name Bad column number Col. no. 0 : Col name Bad column number Col. no. 1 : Col name A Col. no. 26 : Col name Z Col. no. 27 : Col name AA Col. no. 701 : Col name ZY Col. no. 702 : Col name ZZ Col. no. 703 : Col name AAA Col. no. 10342 : Col name OGT Col. no. 397645 : Col name VPFA

Cheers,

JohnGG