首页 > 其他 > 详细

Excel 列名和列序号转换

时间:2017-11-29 15:40:41      阅读:446      评论:0      收藏:0      [点我收藏+]

      #region - 由数字转换为Excel中的列字母 -

      public static int ToIndex(string columnName)
      {
          if (!Regex.IsMatch(columnName.ToUpper(), @"[A-Z]+")) { throw new Exception("invalid parameter"); }

          int index = 0;
          char[] chars = columnName.ToUpper().ToCharArray();
          for (int i = 0; i < chars.Length; i++)
          {
              index += ((int)chars[i] - (int)‘A‘ + 1) * (int)Math.Pow(26, chars.Length - i - 1);
          }
          return index - 1;
      }


      public static string ToName(int index)
      {
          if (index < 0) { throw new Exception("invalid parameter"); }

          List<string> chars = new List<string>();
          do
          {
              if (chars.Count > 0) index--;
              chars.Insert(0, ((char)(index % 26 + (int)‘A‘)).ToString());
              index = (int)((index - index % 26) / 26);
          } while (index > 0);

          return String.Join(string.Empty, chars.ToArray());
      }

      #endregion

  

Excel 列名和列序号转换

原文:http://www.cnblogs.com/lhlong/p/7920408.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!