zoukankan      html  css  js  c++  java
  • Excel列字母与数字的转换

    最近工作中发现需要转换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/

  • 相关阅读:
    精益软件度量——实践者的观察与思考读书笔记三
    JS数组操作
    webpack开发环境所需要的插件
    vim 操作
    关于http的npm包
    闭包模式
    一般系统架构的设计
    工作心得
    UML知识
    express源码剖析4
  • 原文地址:https://www.cnblogs.com/publicbill/p/1519825.html
Copyright © 2011-2022 走看看