Click here to Skip to main content
Click here to Skip to main content

Base26 Number Encoding/Generate Excel Columns

By , 2 May 2011
 

Ever needed to convert an Excel Column Letter to a number or vice versa?  Here’s a couple of extension methods to do it:

   1: public static string ToLetterEncoded(this Int32 numberToEncode)
   2: {
   3:     if (numberToEncode <= 0) throw new ArgumentOutOfRangeException(
              "numberToEncode", numberToEncode, "Value must be greater than zero");
   4:     numberToEncode--;
   5:     if (numberToEncode >= 0 && numberToEncode < 26)
   6:         return ((char)('A' + numberToEncode)).ToString();
   7:     else
   8:         return ToLetterEncoded(numberToEncode / 26) + 
                  ToLetterEncoded(numberToEncode % 26 + 1);
   9: }

 

   1: public static Int32 FromLetterEncodedInt32(this string letterEncodedNumber)
   2: {
   3:     if (letterEncodedNumber.IsNullOrWhiteSpace()) throw new ArgumentNullException(
              "letterEncodedNumber");
          //smallest column first
   4:     char[] letters = 
              letterEncodedNumber.ToUpperInvariant().ToCharArray().Reverse().ToArray(); 
   5:     if (letters.Where(c => !char.IsLetter(c)).Any()) throw new ArgumentOutOfRangeException(
              "letterEncodedNumber", 
              "Encoded Number must only contain the letters A-Z");
   6:     int[] numbers = letters.Select(c => (((int)c - 'A') + 1)).ToArray();
   7:     Int32 columnNumber = 0;
   8:     for (int i = 0; i < letters.Length; i++)
   9:     {
  10:         columnNumber += (Int32)Math.Pow(26, i) * numbers[i];
  11:     }
  12:     return columnNumber;
 13: }

I’ve used Int32 to represent the type of integer that you’re en(de)coding, for easy find ‘n’ replace.

These will only work for positive integer (1 and over).

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Martin Jarvis
Software Developer (Senior) Freestyle Interactive Ltd
United Kingdom United Kingdom
Member
I'm a lead developer for Freestyle Interactive Ltd where we create many wonderful websites built on Microsofts ASP.Net and Ektron CMS.
 
I've been developing .Net applications (both Windows and Web) since 2002.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130516.1 | Last Updated 2 May 2011
Article Copyright 2011 by Martin Jarvis
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid