views:

339

answers:

4

How to find column's name or header?

For example if i select column 5 in excel means i want the result as "E". How to get the alphabet or letter corresponding to column no.

Please help me with the code

A: 
public static string GetColumnName(int columnNumber)
{
    const string letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    string columnName = "";

    while (columnNumber > 0)
    {
        columnName = letters[(columnNumber - 1) % 26] + columnName;
        columnNumber = (columnNumber - 1) / 26;
    }

    return columnName;
}
LukeH
hmm.. and if there are more than 26 columns? AA, AB, AC etc
Ahmad
apologies..I realized this works.. http://stackoverflow.com/questions/181596/how-to-convert-a-column-number-eg-127-into-an-excel-column-eg-aa
Ahmad
A: 

I noticed that you keep asking questions but never mark anyone's reply as answer... dunno why people will want to help you if you keep that up...!!!

code4life
Because we don't care about the stupid number next to our names? P.S., that's not an answer.
Ken
A: 

What about using Application.ActiveCell.get_Address(true, true, Excel.AlReferenceStyle.xlA1, missing, missing) and then parse the result string or use a RegEx to get the column heading?

I simply used:

string location = Application.ActiveCell.get_Address(true, true, Excel.AlReferenceStyle.xlA1, missing, missing);
string tokens = x.Split("$".ToCharArray());
MessageBox.Show(String.Format("Column {0}", result[0]));
Ahmad
A: 

The following is a complete method which gives you the corresponding alphabet for an integer value that is passed.

private String Number2String(int number, bool isCaps)
    {
        int number1 = number / 27;
        int number2 = number - (number1 * 26);
        if (number2 > 26)
        {
            number1 = number1 + 1;
            number2 = number - (number1 * 26);
        }
        Char a = (Char)((isCaps ? 65 : 97) + (number1 - 1));
        Char b = (Char)((isCaps ? 65 : 97) + (number2 - 1));
        Char c = (Char)((isCaps ? 65 : 97) + (number - 1));
        string d = String.Concat(a, b);
        if (number <= 26)
            return c.ToString();
        else
            return d;
    }
SEVUDAS