数值转换成Excel列名

相信这个问题解决方案在网上早已流传,下面是我自己的解决方法。如有雷同,只能说明我们的想法是一样,请见谅。

View Code
 1         public static string strResult = "";
 2         /// <summary>
 3         /// 将指定数值转换成Excel列名
 4         /// </summary>
 5         /// <param name="colIndex">数值</param>
 6         /// <returns>返回数值对应的Excel列名</returns>
 7         public static string NumbertoString(int colIndex)
 8         {
 9             int once = colIndex / 26;
10             int twice = colIndex % 26;
11             strResult = ((char)(twice - 1 + 'A')).ToString() + strResult;
12             if (once > 26)
13             {
14                 NumbertoString(once);
15             }
16             else
17             {
18                 strResult = ((char)(once - 1 + 'A')).ToString() + strResult;
19             }
20             return strResult;
21         }

注意:调用此方法之前一定要保证strResult变量为空,如果不是,则调用前要赋空。

下面是网上评论为比较好的方法:

View Code
 1 /// <summary>
 2         /// 将指定数值转换成Excel列名
 3         /// </summary>
 4         /// <param name="colIndex">数值</param>
 5         /// <returns>返回数值对应的Excel列名</returns>
 6         public static string NumbertoString(int colIndex)
 7         {
 8             string strResult = ""; // result                
 9             int iRest = 0;         // remainder                  
10             while (colIndex != 0)
11             {
12                 iRest = colIndex % 26;
13                 char ch = ' ';
14                 if (iRest == 0)
15                 {
16                     ch = 'Z';
17                 }
18                 else
19                 {
20                     ch = (char)(iRest - 1 + 'A');
21                 }
22 
23                 strResult = ch.ToString() + strResult;
24                 if (strResult[0] == 'Z')
25                 {
26                     colIndex = colIndex / 26 - 1;
27                 }
28                 else
29                 {
30                     colIndex /= 26;
31                 }
32             }
33             return strResult;
34         }


 

原文地址:https://www.cnblogs.com/pfcan66/p/2679128.html