Excel 数字列名(序号)与字母列名(序号)的转换

2012年2月6日作者:enet

 

来自: http://www.tal-rasha.com/archives/254.html
写代码使用到的Excel索引间的转换,其实就是十进制和二十六进制间的转换

        /// <summary>
        /// 用于excel表格中字母转成索引,从1对应A开始
        /// </summary>
        /// <param name="column">号</param>
        /// <returns>索引</returns>
        private int ColumnToIndex(string column)
        {
            if (!Regex.IsMatch(column.ToUpper(), @"[A-Z]+"))
            {
                throw new Exception("Invalid parameter");
            }
            int index = 0;
            char[] chars = column.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;
        }

        /// <summary>
        /// 用于将excel表格中索引转成字母,从A对应1开始
        /// </summary>
        /// <param name="index">索引</param>
        /// <returns>号</returns>
        private string IndexToColumn(int index)
        {
            if (index <= 0)
            {
                throw new Exception("Invalid parameter");
            }
            index--;
            string column = string.Empty;
            do
            {
                if (column.Length > 0)
                { index--;
                }
                column = ((char)(index % 26 + (int)'A')).ToString() + column;
                index = (int)((index - index % 26) / 26);
            } while (index > 0);
            return column;
        }