Bestcomy.net blog

Coding for funny
随笔 - 118, 文章 - 1, 评论 - 2920, 阅读 - 89万

导航

Excel列名转换

Posted on   bestcomy  阅读(2099)  评论(2编辑  收藏  举报

最近工作中发现需要转换Excel列名,例如A列序号为0,Z列序号为25,ZB列则为27
发现字母列名实际为26进制,于是写了如下Helper Class来解决我的问题:

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


测试代码:
1 
2             string[] cols = new string[] { "A""AA""AAA""Z""ZZ""ZZZ""ABC""CBA""XZB" };
3             for (int i = 0; i < cols.Length; i++)
4             {
5                 Console.WriteLine("{0} == {1}", cols[i], ExcelColumnTranslator.ToName(ExcelColumnTranslator.ToIndex(cols[i])));
6             }


测试输出:
A == A
AA == AA
AAA == AAA
Z == Z
ZZ == ZZ
ZZZ == ZZZ
ABC == ABC
CBA == CBA
XZB == XZB

仅供参考
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示