Created
March 21, 2016 13:26
-
-
Save cleytonferrari/8c14b710c690dd9a0b97 to your computer and use it in GitHub Desktop.
Logica pra gerar nomes sequencial igual as colunas do excel.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
namespace LogicaSequencial | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
for (int i = 0; i < 100; i++) | |
{ | |
string code = ExcelColumnFromNumber(i); | |
Console.WriteLine(i + ": " + code + "->" + NumberFromExcelColumn(code).ToString()); | |
} | |
} | |
public static string ExcelColumnFromNumber(int column) | |
{ | |
string columnString = ""; | |
decimal columnNumber = column; | |
while (columnNumber > 0) | |
{ | |
decimal currentLetterNumber = (columnNumber - 1) % 26; | |
char currentLetter = (char)(currentLetterNumber + 65); | |
columnString = currentLetter + columnString; | |
columnNumber = (columnNumber - (currentLetterNumber + 1)) / 26; | |
} | |
return columnString; | |
} | |
public static int NumberFromExcelColumn(string column) | |
{ | |
int retVal = 0; | |
string col = column.ToUpper(); | |
for (int iChar = col.Length - 1; iChar >= 0; iChar--) | |
{ | |
char colPiece = col[iChar]; | |
int colNum = colPiece - 64; | |
retVal = retVal + colNum * (int)Math.Pow(26, col.Length - (iChar + 1)); | |
} | |
return retVal; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment