kingline
 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......

分类:

技术点:

相关文章:

  • 2021-12-22
  • 2021-07-18
  • 2021-12-20
  • 2021-12-22
  • 2021-11-06
  • 2021-12-22
  • 2021-12-22
  • 2021-08-06
猜你喜欢
  • 2021-08-06
  • 2021-09-13
  • 2021-12-22
  • 2021-08-06
  • 2021-07-10
  • 2019-11-06
相关资源
相似解决方案