What is the algorithm to convert an Excel Column Letter into its Number?

Viewed 46182

I need an algorithm to convert an Excel Column letter to its proper number.

The language this will be written in is C#, but any would do or even pseudo code.

Please note I am going to put this in C# and I don't want to use the office dll.

For 'A' the expected result will be 1

For 'AH' = 34

For 'XFD' = 16384

11 Answers
public static int ExcelColumnNameToNumber(string columnName)
{
    if (string.IsNullOrEmpty(columnName)) throw new ArgumentNullException("columnName");

    columnName = columnName.ToUpperInvariant();

    int sum = 0;

    for (int i = 0; i < columnName.Length; i++)
    {
        sum *= 26;
        sum += (columnName[i] - 'A' + 1);
    }

    return sum;
}
int result = colName.Select((c, i) =>
    ((c - 'A' + 1) * ((int)Math.Pow(26, colName.Length - i - 1)))).Sum();
int col = colName.ToCharArray().Select(c => c - 'A' + 1).
          Reverse().Select((v, i) => v * (int)Math.Pow(26, i)).Sum();

Loop through the characters from last to first. Multiply the value of each letter (A=1, Z=26) times 26**N, add to a running total. My string manipulation skill in C# is nonexistent, so here is some very mixed pseudo-code:

sum=0;
len=length(letters);
for(i=0;i<len;i++)
  sum += ((letters[len-i-1])-'A'+1) * pow(26,i);

Could you perhaps treat it like a base 26 number, and then substitute letters for a base 26 number?

So in effect, your right most digit will always be a raw number between 1 and 26, and the remainder of the "number" (the left part) is the number of 26's collected? So A would represent one lot of 26, B would be 2, etc.

As an example:

B = 2 = Column 2
AB = 26 * 1(A) + 2 = Column 28
BB = 26 * 2(B) + 2 = Column 54
DA = 26 * 4(D) + 1 = Column 105

etc

Here is a basic c++ answer for those who are intrested in c++ implemention.

int titleToNumber(string given) {
    int power=0;
    int res=0;
    for(int i=given.length()-1;i>=0;i--)
    {
        char c=given[i];
        res+=pow(26,power)*(c-'A'+1);
        power++;    
    }
    return res;     
    }

For this purpose I use only one line:

int ColumnNumber = Application.Range[MyColumnName + "1"].Column;  
Related