Translate a column index into an Excel Column Name

前端 未结 15 2348
花落未央
花落未央 2020-11-27 20:41

Given a columns\' index, how can you get an Excel column name?

The problem is trickier than it sounds because it\'s not just base-26. The columns

15条回答
  •  无人及你
    2020-11-27 21:03

    Here is my answer in C#, for translating both ways between column index and column name.

    /// 
    /// Gets the name of a column given the index, as it would appear in Excel.
    /// 
    /// The zero-based column index number.
    /// The name of the column.
    /// Column 0 = A, 26 = AA.
    public static string GetColumnName(int columnIndex)
    {
        if (columnIndex < 0) throw new ArgumentOutOfRangeException("columnIndex", "Column index cannot be negative.");
    
        var dividend = columnIndex + 1;
        var columnName = string.Empty;
    
        while (dividend > 0)
        {
            var modulo = (dividend - 1) % 26;
            columnName = Convert.ToChar(65 + modulo) + columnName;
            dividend = (dividend - modulo) / 26;
        }
    
        return columnName;
    }
    
    /// 
    /// Gets the zero-based column index given a column name.
    /// 
    /// The column name.
    /// The index of the column.
    public static int GetColumnIndex(string columnName)
    {
        var index = 0;
        var total = 0;
        for (var i = columnName.Length - 1; i >= 0; i--)
            total += (columnName.ToUpperInvariant()[i] - 64) * (int)Math.Pow(26, index++);
    
        return total - 1;
    }
    

提交回复
热议问题