Excel替换数字字母替换字体对应的字母

字母和数字的转换——Excel列名 - daixinet - 博客园
&&& 在用代码操作Excel的过程中(如OpenXml),会用到把列名转化为数字,然后再进行计算确认列处理。
 & 把列名转化为数字很容易实现定位。下面分享的这两个方法的主要作用是:
    (1)把字母转为数字, 如1转为A,AA转为27 ,然后进行处理;
    (2)把数字转为字母,A-&1,27-&AA&&(这个比较常用)。
1、字母转数字
&&& 思想:&从字符串的最后一位到第一位,乘以26的幂,依次相加
  算法: 26^0 *&(最后一位 ) + 26 ^ 1 * (前一位 ) + && + 26 ^ n * (第一位)。
private int MoreCharToInt(string value) 2
int rtn = 0; 4
int powIndex = 0; 5
for (int i = value.Length - 1; i &= 0; i--) 7
int tmpInt = value[i]; 9
tmpInt -= 64;10 11
rtn += (int)Math.Pow(26, powIndex) * tmpI12
powIndex++;13
2、数字转为字母
&&& 思想: 字母对应的数字的算法为:26^0 * A + 26 ^ 1 * A &&,
      按照这个规律 每次除以26,就可以得到每一位的值,然后进行转换。
      但是有个小问题,就是如果这一位是字符 &Z& 的话,就会进位,转换完后,处理进位的值即可(这里是关键哦)。
private string IntToMoreChar(int value) 2
string rtn = string.E 4
List&int& iList = new List&int&(); 5
//To single Int 7
while (value / 26 != 0 || value % 26 != 0) 8
iList.Add(value % 26);10
value /= 26;11
//Change 0 To 2614
for (int j = 0; j & iList.Count - 1; j++)15
if (iList[j] == 0)17
iList[j + 1] -= 1;19
iList[j] = 26;20
//Remove 0 at last24
if (iList[iList.Count - 1] == 0)25
iList.Remove(iList[iList.Count - 1]);27
//To String30
for (int j = iList.Count - 1; j &= 0; j--)31
char c = (char)(iList[j] + 64);33
rtn += c.ToString();34
  小弟不才, 花了一段时间才想出来的,希望对大家能有所帮助吧!
  以后对于 功能、方法的算法,我会尽量分享出来,供大家讨论,以获取更好的思路。

我要回帖

更多关于 excel字母替换成数字 的文章

 

随机推荐