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

转载于:https://www.cnblogs.com/kingline/p/9618297.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值