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; }