Excel列字母和数字的转换

时间:2024-03-05 18:56:35

网上看的,收藏备用

//用于excel表格中列号字转成数字,返回的列号索引从1开始
        public  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;
        }
 //用于将数字转成excel表格中列号字母,返回的列号索引从A开始,从A对应1开始
        public string ToName(int index)
        {
            if (index <= 0)
                throw new Exception("invaild parameter");
            
            index--;
            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());
        }