是否有人将算法或逻辑转换为1,B为2,...,Z为26,然后是AA到27,AB到28等。
换句话说,将列索引转换为Excel中的列引用。
答案 0 :(得分:34)
这是一个简单的LINQ表达式:
static int TextToNumber(this string text) {
return text
.Select(c => c - 'A' + 1)
.Aggregate((sum, next) => sum*26 + next);
}
此测试
Console.WriteLine(" A -> " + "A".TextToNumber());
Console.WriteLine(" B -> " + "B".TextToNumber());
Console.WriteLine(" Z -> " + "Z".TextToNumber());
Console.WriteLine("AA -> " + "AA".TextToNumber());
Console.WriteLine("AB -> " + "AB".TextToNumber());
将产生此输出:
A -> 1
B -> 2
Z -> 26
AA -> 27
AB -> 28
<强>更新强> 这是相同的代码,但针对的是.NET 2.0:
static int TextToNumber(string text) {
int sum = 0;
foreach (char c in text) {
sum = sum*26 + c - 'A' + 1;
}
return sum;
}
答案 1 :(得分:25)
看看这些
/// <summary>
/// 1 -> A<br/>
/// 2 -> B<br/>
/// 3 -> C<br/>
/// ...
/// </summary>
/// <param name="column"></param>
/// <returns></returns>
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;
}
/// <summary>
/// A -> 1<br/>
/// B -> 2<br/>
/// C -> 3<br/>
/// ...
/// </summary>
/// <param name="column"></param>
/// <returns></returns>
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;
}
答案 2 :(得分:2)
如果你喜欢在客户端上完成,这是一个JavaScript代码
<script type="text/javascript" lang="javascript">
function Alphabet2Numeric(mystr) {
mystr = mystr.toUpperCase(); //Hence the ASCII code 64 down there
var sum = 0;
for (var i = 0; i < mystr.length; i++) {
sum = sum * 26 + mystr.charCodeAt(i) - 64; //returns 1 for 'a' and 2 for 'b' so on and so forth.
}
return sum;
}
</script>
答案 3 :(得分:0)
同样的问题,不同的语言:PHP。
function charToInt($char)
{
$array = array_flip(range(a, z));
return $array[$char] + 1;
}
echo charToInt('c');
outputs: 3
答案 4 :(得分:0)