1 public static int NameToIndex(string columnName) 2 { 3 if (!Regex.IsMatch(columnName.ToUpper(), @"[A-Z]+")) { throw new Exception("参数非法!"); } 5 int index = 0; 6 char[] chars = columnName.ToUpper().ToCharArray(); 7 for (int i = 0; i < chars.Length; i++) 8 { 9 index += ((int)chars[i] - (int)'A' + 1) * (int)Math.Pow(26, chars.Length - i - 1); 10 } 11 return index; 12 } 13 14 /// <summary> 15 /// 1、2、3 转换A、B、C 18 /// <param name="index"></param> 19 /// <returns></returns> 20 public static string IndexToName(int index) 21 { 22 if (index < 0) { throw new Exception("参数非法!"); } 24 List<string> chars = new List<string>(); 25 do 26 { 27 if (chars.Count > 0) index--; 28 string tempchar = ""; 29 if (chars.Count == 0) 30 { 31 tempchar = ((char)(index % 26 + (int)'A' - 1)).ToString(); 32 } 33 else { 34 tempchar = ((char)(index % 26 + (int)'A')).ToString(); 35 } 36 chars.Insert(0, tempchar); 37 index = (int)((index - index % 26) / 26); 38 } while (index > 0); 39 return String.Join(string.Empty, chars.ToArray()); 40 }