tags:

views:

779

answers:

2

I was wondering what is the best way to convert excel sheet column names into numbers.

I'm working with Excel Package, a good library to handle .xlsx documents. This library unfortunately doesn't have this functionality included.

OBS: The first column, A, corresponds to number 1 in this library.

+11  A: 

This function should work for an arbitrary length column name.

public static int GetColumnNumber(string name)
{
    int number = 0;
    int pow = 1;
    for (int i = name.Length - 1; i >= 0; i--)
    {
        number += (name[i] - 'A' + 1) * pow;
        pow *= 26;
    }

    return number;
}
Noldorin
nice! !
Eoin Campbell
really good, man. I was doing it, but the method was way bigger than this simple solution.
Victor Rodrigues
Thanks. And yeah, I think this seems pretty simple, though feel free to suggest any optimisations...
Noldorin
Great job on this one! :) Helped a lot...
Leniel Macaferi
+5  A: 

I had to deal with this a few months ago. The inverse - column index to column name - is fun, too, and becomes really messy if you try to solve it with a zero based index not recognizing that this complicates things. It could be so simple if it would be a normal polyadic numeral system ...

Here is a simplified version of my solution as a extension method without error handling and all that stuff.

public static Int32 ToOneBasedIndex(this String name)
{
    return name.ToUpper().
       Aggregate(0, (column, letter) => 26 * column + letter - 'A' + 1);
}
Daniel Brückner
Man, that is tight. +1
wcm