ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

ExcelColumnName

Returns the excel column name from a column index

Source

public static string ExcelColumnName(this int index)
{
	var chars = new [] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
		'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };

	index -= 1; //adjust so it matches 0-indexed array rather than 1-indexed column

	string columnName;

	var quotient = index / 26;
	if (quotient > 0)
		columnName = ExcelColumnName(quotient) + chars[index % 26];
	else
		columnName = chars[index % 26].ToString();

	return columnName;
}

Example

string columnName = 3.ExcelColumnName();

Author: Victor Rodrigues

Submitted on: 13 mei 2009

Language: C#

Type: System.Int32

Views: 4993