Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Translate a column index into an Excel Column Name

Tags:

.net

excel

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 don't wrap over like normal digits would. Even the Microsoft Support Example doesn't scale beyond ZZZ.

Disclaimer: This is some code I had done a while back, and it came across my desktop again today. I thought it was worthy of posting here as a pre-answered question.

like image 931
Joel Coehoorn Avatar asked Nov 17 '08 22:11

Joel Coehoorn


People also ask

How do you set a column to index in Excel?

An index column is also added to an Excel worksheet when you load it. To open a query, locate one previously loaded from the Power Query Editor, select a cell in the data, and then select Query > Edit. For more information see Create, load, or edit a query in Excel (Power Query). Select Add Column > Index Column.

How do I get column header name in Excel?

Go to Table Tools > Design on the Ribbon. In the Table Style Options group, select the Header Row check box to hide or display the table headers.


1 Answers

The answer I came up with is to get a little recursive. This code is in VB.Net:

Function ColumnName(ByVal index As Integer) As String
        Static chars() As Char = {"A"c, "B"c, "C"c, "D"c, "E"c, "F"c, "G"c, "H"c, "I"c, "J"c, "K"c, "L"c, "M"c, "N"c, "O"c, "P"c, "Q"c, "R"c, "S"c, "T"c, "U"c, "V"c, "W"c, "X"c, "Y"c, "Z"c}

        index -= 1 ' adjust so it matches 0-indexed array rather than 1-indexed column

        Dim quotient As Integer = index \ 26 ' normal / operator rounds. \ does integer division, which truncates
        If quotient > 0 Then
               ColumnName = ColumnName(quotient) & chars(index Mod 26)
        Else
               ColumnName = chars(index Mod 26)
        End If
End Function

And in C#:

string ColumnName(int index)
{
    index -= 1; //adjust so it matches 0-indexed array rather than 1-indexed column

    int quotient = index / 26;
    if (quotient > 0)
        return ColumnName(quotient) + chars[index % 26].ToString();
    else
        return chars[index % 26].ToString();
}
private char[] chars = new char[] {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};

The only downside it that it uses 1-indexed columns rather than 0-indexed.

like image 177
Joel Coehoorn Avatar answered Oct 14 '22 10:10

Joel Coehoorn