在用代码操作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)
- {
- int rtn = 0;
- int powIndex = 0;
- for (int i = value.Length - 1; i >= 0; i--)
- {
- int tmpInt = value[i];
- tmpInt -= 64;
- rtn += (int)Math.Pow(26, powIndex) * tmpInt;
- powIndex++;
- }
- return rtn;
- }
2、数字转为字母
思想: 字母对应的数字的算法为:26^0 * A + 26 ^ 1 * A ……,
按照这个规律 每次除以26,就可以得到每一位的值,然后进行转换。
但是有个小问题,就是如果这一位是字符 ‘Z’ 的话,就会进位,转换完后,处理进位的值即可(这里是关键哦)。
- private string IntToMoreChar(int value)
- {
- string rtn = string.Empty;
- List<int> iList = new List<int>();
- //To single Int
- while (value / 26 != 0 || value % 26 != 0)
- {
- iList.Add(value % 26);
- value /= 26;
- }
- //Change 0 To 26
- for (int j = 0; j < iList.Count - 1; j++)
- {
- if (iList[j] == 0)
- {
- iList[j + 1] -= 1;
- iList[j] = 26;
- }
- }
- //Remove 0 at last
- if (iList[iList.Count - 1] == 0)
- {
- iList.Remove(iList[iList.Count - 1]);
- }
- //To String
- for (int j = iList.Count - 1; j >= 0; j--)
- {
- char c = (char)(iList[j] + 64);
- rtn += c.ToString();
- }
- return rtn;
- }
小弟不才, 花了一段时间才想出来的,希望对大家能有所帮助吧!
以后对于 功能、方法的算法,我会尽量分享出来,供大家讨论,以获取更好的思路