在用代碼操作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 }
小弟不才, 花了一段時間才想出來的,希望對大家能有所協助吧!
以後對於 功能、方法的演算法,我會盡量分享出來,供大家討論,以擷取更好的思路。