It might help to realize that the column name is essentially a base-26 number, using A as '0'. Then a div+mod loop while anything is left would only require building a 26 character alphabet. (for all I know, this could be how the XLS utils mentioned above handle it).

There are a couple of fencepost errors here. Fix coming shortly Ok, this is not quite a base-26 number. The least significant digit is treated slightly different than all other digits.

sub mlx_xls2col { my $col = shift; my $alphabet = shift || [ 'A' .. 'Z' ]; my $alphabet_size = scalar( @$alphabet ); my $result = ''; my $remainder = $col; while ( $remainder ) { my $letter = $remainder % $alphabet_size; my $adj = length( $result ) ? -1 : 0; # Not quite a base-26 + number $result = $alphabet->[$letter + $adj] . $result; $remainder = int( $remainder / $alphabet_size ); } $result ||= $alphabet->[0]; $result; } print mlx_xls2col( 0 ), "\n"; print mlx_xls2col( 1 ), "\n"; print mlx_xls2col( 2 ), "\n"; print mlx_xls2col( 24 ), "\n"; print mlx_xls2col( 25 ), "\n"; print mlx_xls2col( 26 ), "\n"; print mlx_xls2col( 27 ), "\n"; print mlx_xls2col( 51 ), "\n"; print mlx_xls2col( 52 ), "\n"; print mlx_xls2col( 53 ), "\n"; __DATA__ A B C Y Z AA AB AZ BA BB

--MidLifeXis


In reply to Re: Get excel column letter from number by MidLifeXis
in thread Get excel column letter from number by bulrush

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.