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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM