Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find the Excel column name that corresponds to a given integer? [duplicate]

How would you determine the column name (e.g. "AQ" or "BH") of the nth column in Excel?

Edit: A language-agnostic algorithm to determine this is the main goal here.

like image 799
goric Avatar asked Aug 22 '08 15:08

goric


People also ask

How do I get column names from column numbers in Excel?

In a row of Excel, e.g. cell A1, enter the column number =column() In the row below, enter =Address(1,A1) This will provide the result $A$1.


2 Answers

I once wrote this function to perform that exact task:

public static string Column(int column) {     column--;     if (column >= 0 && column < 26)         return ((char)('A' + column)).ToString();     else if (column > 25)         return Column(column / 26) + Column(column % 26 + 1);     else         throw new Exception("Invalid Column #" + (column + 1).ToString()); } 
like image 106
Joseph Sturtevant Avatar answered Oct 09 '22 21:10

Joseph Sturtevant


Here is the cleanest correct solution I could come up with (in Java, but feel free to use your favorite language):

String getNthColumnName(int n) {     String name = "";     while (n > 0) {         n--;         name = (char)('A' + n%26) + name;         n /= 26;     }     return name; } 

But please do let me know of if you find a mistake in this code, thank you.

like image 40
Samuel Audet Avatar answered Oct 09 '22 23:10

Samuel Audet