Converting Column Number to Column Letter and Reverse in Excel using C#

Converting Column Number to Column Letter and Reverse in Excel using C#

Column:

Excel column can be referenced by its name using Range object or by its number using Cells method. Sometimes developer may in need of converting column number to column letter. This usually happens when you are playing between Cell and Range object based on the situation and easy to implement. Following code will give your dynamic solution of this problem.

Code example: to convert a number to column letter

public static string ConvertColumnNumberToLetter(int colNumber)
{
	try
	{
		int n = 0;
		int c = 0;
		string s = null;

		n = colNumber;
		do
		{
			c = ((n - 1) % 26);
			s = Convert.ToChar(c + 65) + s;
			n = (n - c) / 26;
		} while (n > 0);
		return s;
	}
	catch (Exception)
	{

		return string.Empty;
	}
}

Code example: to convert column letter to column index

public static int ColumnLetterToColumnIndex(string columnLetter)
{
	try
	{
		columnLetter = columnLetter.ToUpper();
		int sum = 0;

		for (int i = 0; i < columnLetter.Length; i++)
		{
			sum *= 26;
			sum += (columnLetter[i] - 'A' + 1);
		}
		return sum;
	}
	catch (Exception ex)
	{
		return 0;
	}
}

Next>>Get List of Unsupported Sheet in C# VSTO

One thought on “Converting Column Number to Column Letter and Reverse in Excel using C#

Leave a Reply

Your email address will not be published. Required fields are marked *