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

        在用代码操作Excel的过程中(如OpenXml),会用到把列名转化为数字,然后再进行计算确认列处理。

       把列名转化为数字很容易实现定位。下面分享的这两个方法的主要作用是:

        (1)把字母转为数字, 如1转为A,AA转为27 ,然后进行处理;

        (2)把数字转为字母,A->1,27->AA……(这个比较常用)。

    1、字母转数字

        思想: 从字符串的最后一位到第一位,乘以26的幂,依次相加

      算法: 26^0 * (最后一位 ) + 26 ^ 1 * (前一位 ) + …… + 26 ^ n * (第一位)。

     1         private int MoreCharToInt(string value)
    2 {
    3 int rtn = 0;
    4 int powIndex = 0;
    5
    6 for (int i = value.Length - 1; i >= 0; i--)
    7 {
    8 int tmpInt = value[i];
    9 tmpInt -= 64;
    10
    11 rtn += (int)Math.Pow(26, powIndex) * tmpInt;
    12 powIndex++;
    13 }
    14
    15 return rtn;
    16 }

    2、数字转为字母

        思想: 字母对应的数字的算法为:26^0 * A + 26 ^ 1 * A ……,

          按照这个规律 每次除以26,就可以得到每一位的值,然后进行转换。

          但是有个小问题,就是如果这一位是字符 ‘Z’ 的话,就会进位,转换完后,处理进位的值即可(这里是关键哦)。

     1         private string IntToMoreChar(int value)
    2 {
    3 string rtn = string.Empty;
    4 List<int> iList = new List<int>();
    5
    6 //To single Int
    7 while (value / 26 != 0 || value % 26 != 0)
    8 {
    9 iList.Add(value % 26);
    10 value /= 26;
    11 }
    12
    13 //Change 0 To 26
    14 for (int j = 0; j < iList.Count - 1; j++)
    15 {
    16 if (iList[j] == 0)
    17 {
    18 iList[j + 1] -= 1;
    19 iList[j] = 26;
    20 }
    21 }
    22
    23 //Remove 0 at last
    24 if (iList[iList.Count - 1] == 0)
    25 {
    26 iList.Remove(iList[iList.Count - 1]);
    27 }
    28
    29 //To String
    30 for (int j = iList.Count - 1; j >= 0; j--)
    31 {
    32 char c = (char)(iList[j] + 64);
    33 rtn += c.ToString();
    34 }
    35
    36 return rtn;
    37 }

       

      小弟不才, 花了一段时间才想出来的,希望对大家能有所帮助吧!

      以后对于 功能、方法的算法,我会尽量分享出来,供大家讨论,以获取更好的思路。

  • 相关阅读:
    Decrease (Judge ver.)
    Raising Modulo Numbers
    最短Hamilton路径
    64位整数乘法
    递归系列——数组和对象的相关递归
    函数内容新增——函数表达式
    数据结构和算法(一)——栈
    (转)jQuery中append(),prepend()与after(),before()的区别
    微信端的user-Agent
    less知识点总结(二)
  • 原文地址:https://www.cnblogs.com/sshoub/p/2121312.html
Copyright © 2011-2022 走看看