您的位置:首页 > 其它

Excel列字母与数字的转换

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

1 public class ExcelColumnTranslator
2 {
3 private ExcelColumnTranslator()
4 {
5 }
6
7 public static int ToIndex(string columnName)
8 {
9 if (!Regex.IsMatch(columnName.ToUpper(), @"[A-Z]+"))
10 throw new Exception("invalid parameter");
11 int index = 0;
12 char[] chars = columnName.ToUpper().ToCharArray();
13 for (int i = 0; i < chars.Length; i++)
14 {
15 index += ((int)chars[i] - (int)'A' + 1) * (int)Math.Pow(26, chars.Length - i - 1);
16 }
17 return index - 1;
18 }
19
20 public static string ToName(int index)
21 {
22 if (index < 0)
23 throw new Exception("invalid parameter");
24 List<string> chars = new List<string>();
25 do
26 {
27 if (chars.Count > 0) index--;
28 chars.Insert(0, ((char)(index % 26 + (int)'A')).ToString());
29 index = (int)((index - index % 26) / 26);
30 } while (index > 0);
31
32 return String.Join(string.Empty, chars.ToArray());
33 }
34 }
35
PHP相关参考:http://www.liuyuanjun.com/internet/php-letter-add-function/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: