Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Column No to Column Letter in Excel/VSTO using C#

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

like image 384
venkat Avatar asked Mar 26 '10 11:03

venkat


3 Answers

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;
}
like image 102
LukeH Avatar answered Sep 20 '22 15:09

LukeH


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]));
like image 28
Ahmad Avatar answered Sep 18 '22 15:09

Ahmad


public static long GetColumnNumber(string columnName)
{
    int letterPos = 0;   
    long columnNumber = 0;
    for (int placeHolder = columnName.Length - 1; placeHolder >= 0; placeHolder--)
    {
        int currentSum = 1;
        for (int multiplier = 0; multiplier < placeHolder; multiplier++)
            currentSum *= 26;
        int letterValue = (int) columnName[letterPos];
        currentSum *= letterValue - 64;
        columnNumber += currentSum;
        if (letterPos != columnName.Length)
            letterPos++;
        //Console.WriteLine(((int)columnName[i]-64) + " = " + columnName[i]);
    }
        return columnNumber;
}
like image 23
friend Avatar answered Sep 21 '22 15:09

friend