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/
发现字母列名实际为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/
相关文章推荐
- 字母和数字的转换——Excel列名
- 将数字转换成Excel表头格式的字母序号
- JS实现excel表头字母和数字的转换
- 字母和数字的转换——Excel列名
- 数字行列转换成excel的字母+数字格式单元格位标,只支持到676横行
- Excel行列数字字母转换实现
- 将Excel的列数以字母表示的字符串转换成数字表示
- [No0000107]C#中 Excel列字母与数字的转换
- excel 数字列 转换成 字母列
- 黄聪:C#中 Excel列字母与数字的转换
- Excel列名 字母和数字的转换
- Excel中列数字与字母的转换(JAVA实现)
- 转载: 黄聪:C#中 Excel列字母与数字的转换
- 解析Excel时列号数字转换为字母
- Excel列字母和数字的转换
- 将Excel中的字母列名转换成数字的算法
- Excel列名 字母和数字的转换
- excel 数字文本转换为纯数字
- Excel中将数字转换为日期格式
- Excel 数字按长度补0,并转换为文本