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
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;
}
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]));
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With