C# – How to convert Excel sheet column names into numbers?

c++excel

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.

Best Solution

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;
}