热门:网页模板.net视频教程JQueryMVCjsonExtJs源码示例三级联动JQuery菜单
您现在的位置:.Net中文社区>> 数据库>>正文内容

字母和数字的转换——Excel列名

发布时间:2011年08月15日点击数: 佚名

    在用代码操作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.     int rtn = 0; 
  3.     int powIndex = 0; 
  4.  
  5.     for (int i = value.Length - 1; i >= 0; i--) 
  6.     { 
  7.         int tmpInt = value[i]; 
  8.         tmpInt -= 64; 
  9.  
  10.         rtn += (int)Math.Pow(26, powIndex) * tmpInt; 
  11.         powIndex++; 
  12.     } 
  13.  
  14.     return rtn; 

2、数字转为字母

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

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

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

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

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

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

本站热点业务

更多模板/案例展示

关于我们 | 联系我们 | 团队日志 | 网站地图 | 网站合作