Excel的A,AC,ACC等转成对应的列索引(从0开始)
2017-06-02 20:00:45 访问(1414) 赞(0) 踩(0)
-
/// <summary>
/// 判断字符串是否A-Z - IsA2Z
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public bool IsA2Z(string str)
{
int iLen = str.Length;
if (iLen == 0)
return false;
for (int i = 0; i < iLen; ++i)
{
if (!(str[i] >= 'A' && str[i] <= 'Z'))
return false;
}
return true;
}
/// <summary>
/// Excel的A,AC,ACC等转成对应的列索引(从0开始)
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public int ExcelColNameToInt(string str)
{
if (str == null||str.Length ==0)
return -1;
str = str.Trim();
if (str.Length == 0)
return -1;
str = str.ToUpper();
if (!IsA2Z(str))
return -1;
int iLen = str.Length;
int charA = (int)'A';
if (iLen == 1)
{
return str[0] - charA;
}
int theResult = 0;
//if (iLen == 2)
//{
// theResult = (str[0] - charA + 1) * 26;
// theResult += str[1] - charA;
// return theResult;
//}
for (int i = 0; i < iLen; ++i)
{
theResult = theResult * 26 + (str[i] - charA + 1);
}
theResult = theResult - 1;
return theResult;
}
-
上一条:
下一条:
相关评论
发表评论