你很幸运,我以前做过一次。我遇到的问题是在 Excel 工作表中没有 0,甚至在双“数字”“数字”中也没有。这意味着您从 a(即 1)开始,然后从 z(即 26)直接进入 aa(27)。这就是为什么不是一个简单的基本转换问题,您需要一些额外的代码来处理这个问题。测试 xanatos 建议的函数结果如下:
NumToLetters(0) --> A
NumToLetters(25) --> Z
NumToLetters(26) --> BA
我的解决方案有更多代码,但它已经针对 Excel 进行了测试并且完全兼容,除了它以 0 而不是 1 开头,这意味着 a 是 0,z 是 25,aa 是 26,zz 701,aaa 是 702 等等) . 如果需要,您可以将其更改为从 1 开始,这相当容易。
private static string mColumnLetters = "zabcdefghijklmnopqrstuvwxyz";
// Convert Column name to 0 based index
public static int ColumnIndexByName(string ColumnName)
{
string CurrentLetter;
int ColumnIndex, LetterValue, ColumnNameLength;
ColumnIndex = -1; // A is the first column, but for calculation it's number is 1 and not 0. however, Index is alsways zero-based.
ColumnNameLength = ColumnName.Length;
for (int i = 0; i < ColumnNameLength; i++)
{
CurrentLetter = ColumnName.Substring(i, 1).ToLower();
LetterValue = mColumnLetters.IndexOf(CurrentLetter);
ColumnIndex += LetterValue * (int)Math.Pow(26, (ColumnNameLength - (i + 1)));
}
return ColumnIndex;
}
// Convert 0 based index to Column name
public static string ColumnNameByIndex(int ColumnIndex)
{
int ModOf26, Subtract;
StringBuilder NumberInLetters = new StringBuilder();
ColumnIndex += 1; // A is the first column, but for calculation it's number is 1 and not 0. however, Index is alsways zero-based.
while (ColumnIndex > 0)
{
if (ColumnIndex <= 26)
{
ModOf26 = ColumnIndex;
NumberInLetters.Insert(0, mColumnLetters.Substring(ModOf26, 1));
ColumnIndex = 0;
}
else
{
ModOf26 = ColumnIndex % 26;
Subtract = (ModOf26 == 0) ? 26 : ModOf26;
ColumnIndex = (ColumnIndex - Subtract) / 26;
NumberInLetters.Insert(0, mColumnLetters.Substring(ModOf26, 1));
}
}
return NumberInLetters.ToString().ToUpper();
}