zoukankan      html  css  js  c++  java
  • 数值转换成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         }


     

  • 相关阅读:
    Asp.net性能优化总结(一)
    Visual C#常用函数和方法集汇总
    ASP.net下大文件上传的解决方案及WebbUpload组件源码
    正则表达式学习
    在Asp.net中为图像加入版权信息
    Cognos 维度函数
    Cognos8.3函数使用手册(二)
    cognos更新步聚
    Cognos8.3函数使用手册(一)
    Cognos 8 报表备份和恢复
  • 原文地址:https://www.cnblogs.com/pfcan66/p/2679128.html
Copyright © 2011-2022 走看看