Skip to content

Instantly share code, notes, and snippets.

@sachintha81
Created June 21, 2017 16:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sachintha81/a00f3874fab81f632d6229deae74f060 to your computer and use it in GitHub Desktop.
Save sachintha81/a00f3874fab81f632d6229deae74f060 to your computer and use it in GitHub Desktop.
Excel Style String Increment
// (1 = A, 2 = B...27 = AA...703 = AAA...)
public static string GetColNameFromIndex(int columnNumber)
{
int dividend = columnNumber;
string columnName = String.Empty;
int modulo;
while (dividend > 0)
{
modulo = (dividend - 1) % 26;
columnName = Convert.ToChar(65 + modulo).ToString() + columnName;
dividend = (int)((dividend - modulo) / 26);
}
return columnName;
}
// (A = 1, B = 2...AA = 27...AAA = 703...)
public static int GetColNumberFromName(string columnName)
{
char[] characters = columnName.ToUpperInvariant().ToCharArray();
int sum = 0;
for (int i = 0; i < characters.Length; i++)
{
sum *= 26;
sum += (characters[i] - 'A' + 1);
}
return sum;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment