0

I have found here http://lateral8.com/articles/2010/3/5/openxml-sdk-20-export-a-datatable-to-excel.aspx a great function

private string getColumnName(int columnIndex)
{
    int dividend = columnIndex;
    string columnName = String.Empty;
    int modifier;

    while (dividend > 0)
    {
        modifier = (dividend - 1) % 26;
        columnName = 
            Convert.ToChar(65 + modifier).ToString() + columnName;
        dividend = (int)((dividend - modifier) / 26);
    }

    return columnName;
}

I would like to do similar thing - provide column name and receive index. For example provide name 'AB' and receive as result index 28. How to do this?

UPDATE:

Surprising, I have found solution in the comments section

here https://stackoverflow.com/a/8739121/907732

and here https://stackoverflow.com/a/4888750/907732

4
  • Possible duplicate - stackoverflow.com/questions/10373561/… Commented Feb 26, 2013 at 11:28
  • @JMK OP asks for inverse method Commented Feb 26, 2013 at 11:30
  • I linked to a question about the inverse method, and yes AB should be 28 Commented Feb 26, 2013 at 11:32
  • 2
    Doesn't AB column have index 28? Commented Feb 26, 2013 at 11:32

1 Answer 1

0
public static string GetColumnName(int index)
{
    const string letters = "ZABCDEFGHIJKLMNOPQRSTUVWXY";

    int NextPos = (index / 26);
    int LastPos = (index % 26);
    if (LastPos == 0) NextPos--;

    if (index > 26)
        return GetColumnName(NextPos) + letters[LastPos];
    else
        return letters[LastPos] + "";
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.