Excel列A、B、C、D----与列序号的转换

 1   public static class ExcelConvert
 2     {
 3         public static int ToExcelIndex(this string columnName)
 4         {
 5             if (!Regex.IsMatch(columnName.ToUpper(), @"[A-Z]+"))
 6                 throw new Exception("错误参数");
 7 
 8             int index = 0;
 9             char[] chars = columnName.ToUpper().Trim().ToCharArray();
10             for(int i = 0; i < chars.Length; i++)
11             {
12                 index += ((int)chars[i] - (int)'A' + 1) * (int)Math.Pow(26, chars.Length - i - 1);
13             }
14             return index - 1;
15         }
16 
17         public static string ToExcelName(this int index)
18         {
19             if(index<0)
20                 throw new Exception("错误参数");
21 
22             List<string> chars = new List<string>();
23             do
24             {
25                 if (chars.Count > 0)
26                     index--;
27                 chars.Insert(0, ((char)(index % 26 + (int)'A')).ToString());
28                 index = (int)((index - index % 26) / 26);
29             } while (index > 0);
30             return String.Join(string.Empty, chars.ToArray());
31         }
32     }

起始下标为0,即A=0,B=1......

猜你喜欢

转载自www.cnblogs.com/kingline/p/9618297.html