Excel的A,AC,ACC等转成对应的列索引(从0开始)(uLong模式)

2017-06-03 09:54:21  访问(1422) 赞(0) 踩(0)

  • 
            /// <summary>
            /// Excel的A,AC,ACC等转成对应的列索引(从0开始)(uLong模式)
            /// </summary>
            /// <param name="str"></param>
            /// <returns></returns>
            public ulong ExcelColNameToULong(string str)
            {
                if (str == null || str.Length == 0)
                {
                    throw new Exception
                        (
                            "方法:"
                            + MethodBase.GetCurrentMethod().ReflectedType.FullName
                            + " "
                            + MethodBase.GetCurrentMethod().ToString()
                            + " 发生异常:"
                            + "string str"
                            + "值为null或trim后为空。"
                        );
                }
    
                str = str.Trim();
    
                if (str.Length == 0)
                {
                    throw new Exception
                           (
                               "方法:"
                               + MethodBase.GetCurrentMethod().ReflectedType.FullName
                               + " "
                               + MethodBase.GetCurrentMethod().ToString()
                               + " 发生异常:"
                               + "string str"
                               + "值为null或trim后为空。"
                           );
                }
    
                str = str.ToUpper();
    
                if (!IsA2Z(str))
                {
                    throw new Exception
                        (
                            "方法:"
                            + MethodBase.GetCurrentMethod().ReflectedType.FullName
                            + " "
                            + MethodBase.GetCurrentMethod().ToString()
                            + " 发生异常:"
                            + "string str"
                            + "值为无效的Excel列项值。"
                        );
                }
    
                int iLen = str.Length;
    
                // 字符串A对应的int值 //
                int charA = (int)'A';
    
                if (iLen == 1)
                {
                    return (ulong)(str[0] - charA);
                }
    
                ulong theResult = 0;
    
                for (int i = 0; i < iLen; ++i)
                {
                    theResult = theResult * 26 + (ulong)(str[i] - charA + 1);
                }
    
                // 索引从0开始,所以减去1 //
                theResult = theResult - 1;
    
                return theResult;
            }
    

  • 输入1:
    输出:

上一条:

下一条:


 
 

相关评论

评论加载中……
 

发表评论

类型:
内容:
  (Alt+Enter)