How to convert a column number (e.g. 127) into an Excel column (e.g. AA)

前端 未结 30 2121
鱼传尺愫
鱼传尺愫 2020-11-22 00:35

How do you convert a numerical number to an Excel column name in C# without using automation getting the value directly from Excel.

Excel 2007 has a possible range o

相关标签:
30条回答
  • 2020-11-22 00:44

    ..And converted to php:

    function GetExcelColumnName($columnNumber) {
        $columnName = '';
        while ($columnNumber > 0) {
            $modulo = ($columnNumber - 1) % 26;
            $columnName = chr(65 + $modulo) . $columnName;
            $columnNumber = (int)(($columnNumber - $modulo) / 26);
        }
        return $columnName;
    }
    
    0 讨论(0)
  • 2020-11-22 00:46

    If anyone needs to do this in Excel without VBA, here is a way:

    =SUBSTITUTE(ADDRESS(1;colNum;4);"1";"")
    

    where colNum is the column number

    And in VBA:

    Function GetColumnName(colNum As Integer) As String
        Dim d As Integer
        Dim m As Integer
        Dim name As String
        d = colNum
        name = ""
        Do While (d > 0)
            m = (d - 1) Mod 26
            name = Chr(65 + m) + name
            d = Int((d - m) / 26)
        Loop
        GetColumnName = name
    End Function
    
    0 讨论(0)
  • 2020-11-22 00:46
    private String getColumn(int c) {
        String s = "";
        do {
            s = (char)('A' + (c % 26)) + s;
            c /= 26;
        } while (c-- > 0);
        return s;
    }
    

    Its not exactly base 26, there is no 0 in the system. If there was, 'Z' would be followed by 'BA' not by 'AA'.

    0 讨论(0)
  • 2020-11-22 00:46

    Another VBA way

    Public Function GetColumnName(TargetCell As Range) As String
        GetColumnName = Split(CStr(TargetCell.Cells(1, 1).Address), "$")(1)
    End Function
    
    0 讨论(0)
  • 2020-11-22 00:47

    Coincise and elegant Ruby version:

    def col_name(col_idx)
        name = ""
        while col_idx>0
            mod     = (col_idx-1)%26
            name    = (65+mod).chr + name
            col_idx = ((col_idx-mod)/26).to_i
        end
        name
    end
    
    0 讨论(0)
  • 2020-11-22 00:48

    Easy with recursion.

    public static string GetStandardExcelColumnName(int columnNumberOneBased)
    {
      int baseValue = Convert.ToInt32('A');
      int columnNumberZeroBased = columnNumberOneBased - 1;
    
      string ret = "";
    
      if (columnNumberOneBased > 26)
      {
        ret = GetStandardExcelColumnName(columnNumberZeroBased / 26) ;
      }
    
      return ret + Convert.ToChar(baseValue + (columnNumberZeroBased % 26) );
    }
    
    0 讨论(0)
提交回复
热议问题