Find Excel column name from a given column number
Last Updated :
17 Aug, 2022
MS Excel columns have a pattern like A, B, C, …, Z, AA, AB, AC, …., AZ, BA, BB, … ZZ, AAA, AAB ….. etc. In other words, column 1 is named “A”, column 2 as “B”, and column 27 as “AA”.
Given a column number, find its corresponding Excel column name. The following are more examples.
Input Output
26 Z
51 AY
52 AZ
80 CB
676 YZ
702 ZZ
705 AAC
Thanks to Mrigank Dembla for suggesting the below solution in a comment.
Suppose we have a number n, let’s say 28. so corresponding to it we need to print the column name. We need to take the remainder with 26.
If the remainder with 26 comes out to be 0 (meaning 26, 52, and so on) then we put ‘Z’ in the output string and new n becomes n/26 -1 because here we are considering 26 to be ‘Z’ while in actuality it’s 25th with respect to ‘A’.
Similarly, if the remainder comes out to be non-zero. (like 1, 2, 3, and so on) then we need to just insert the char accordingly in the string and do n = n/26.
Finally, we reverse the string and print.
Example:
n = 700
The remainder (n%26) is 24. So we put ‘X’ in the output string and n becomes n/26 which is 26.
Remainder (26%26) is 0. So we put ‘Z’ in the output string and n becomes n/26 -1 which is 0.
Following is the implementation of the above approach.
C++
#include <bits/stdc++.h>
#define MAX 50
using namespace std;
void printString(int n)
{
char str[MAX];
int i = 0;
while (n > 0) {
int rem = n % 26;
if (rem == 0) {
str[i++] = 'Z';
n = (n / 26) - 1;
}
else
{
str[i++] = (rem - 1) + 'A';
n = n / 26;
}
}
str[i] = '\0';
reverse(str, str + strlen(str));
cout << str << endl;
return;
}
int main()
{
printString(26);
printString(51);
printString(52);
printString(80);
printString(676);
printString(702);
printString(705);
return 0;
}
|
Java
public class ExcelColumnTitle {
private static void printString(int columnNumber)
{
StringBuilder columnName = new StringBuilder();
while (columnNumber > 0) {
int rem = columnNumber % 26;
if (rem == 0) {
columnName.append("Z");
columnNumber = (columnNumber / 26) - 1;
}
else
{
columnName.append((char)((rem - 1) + 'A'));
columnNumber = columnNumber / 26;
}
}
System.out.println(columnName.reverse());
}
public static void main(String[] args)
{
printString(26);
printString(51);
printString(52);
printString(80);
printString(676);
printString(702);
printString(705);
}
}
|
Python
MAX = 50
def printString(n):
string = ["\0"] * MAX
i = 0
while n > 0:
rem = n % 26
if rem == 0:
string[i] = 'Z'
i += 1
n = (n / 26) - 1
else:
string[i] = chr((rem - 1) + ord('A'))
i += 1
n = n / 26
string[i] = '\0'
string = string[::-1]
print "".join(string)
printString(26)
printString(51)
printString(52)
printString(80)
printString(676)
printString(702)
printString(705)
|
C#
using System;
class GFG{
static String reverse(String input)
{
char[] reversedString = input.ToCharArray();
Array.Reverse(reversedString);
return new String(reversedString);
}
private static void printString(int columnNumber)
{
String columnName = "";
while (columnNumber > 0)
{
int rem = columnNumber % 26;
if (rem == 0)
{
columnName += "Z";
columnNumber = (columnNumber / 26) - 1;
}
else
{
columnName += (char)((rem - 1) + 'A');
columnNumber = columnNumber / 26;
}
}
columnName = reverse(columnName);
Console.WriteLine(columnName.ToString());
}
public static void Main(String[] args)
{
printString(26);
printString(51);
printString(52);
printString(80);
printString(676);
printString(702);
printString(705);
}
}
|
Javascript
<script>
function printString(columnNumber)
{
let columnName = [];
while (columnNumber > 0) {
let rem = columnNumber % 26;
if (rem == 0) {
columnName.push("Z");
columnNumber = Math.floor(columnNumber / 26) - 1;
}
else
{
columnName.push(String.fromCharCode((rem - 1) + 'A'.charCodeAt(0)));
columnNumber = Math.floor(columnNumber / 26);
}
}
document.write(columnName.reverse().join("")+"<br>");
}
printString(26);
printString(51);
printString(52);
printString(80);
printString(676);
printString(702);
printString(705);
</script>
|
Output
Z
AY
AZ
CB
YZ
ZZ
AAC
Time Complexity: O(log26n), as we are using a loop and in each traversal, we decrement by floor division of 26.
Auxiliary Space: O(50), as we are using extra space for storing the result.
Method 2
The problem is similar to converting a decimal number to its binary representation but instead of a binary base system where we have two digits only 0 and 1, here we have 26 characters from A-Z.
So, we are dealing with base 26 instead of base binary.
That’s not where the fun ends, we don’t have zero in this number system, as A represents 1, B represents 2 and so on Z represents 26.
To make the problem easily understandable, we approach the problem in two steps:
- Convert the number to base 26 representation, considering we have 0 also in the system.
- Change the representation to the one without having 0 in its system.
HOW? Here is an example
Step 1:
Consider we have number 676, How to get its representation in the base 26 system? In the same way, we do for a binary system, Instead of division and remainder by 2, we do division and remainder by 26.
Base 26 representation of 676 is : 100
Step2
But Hey, we can’t have zero in our representation. Right? Because it’s not part of our number system. How do we get rid of zero? Well it’s simple, but before doing that let’s remind one simple math trick:
Subtraction:
5000 - 9, How do you subtract 9 from 0 ? You borrow
from next significant bit, right.
- In a decimal number system to deal with zero, we borrow 10 and subtract 1 from the next significant.
- In the Base 26 Number System to deal with zero, we borrow 26 and subtract 1 from the next significant bit.
So Convert 10026 to a number system that does not have ‘0’, we get (25 26)26
Symbolic representation of the same is: YZ
Here is the implementation of the same:
C++
#include <iostream>
using namespace std;
void printString(int n)
{
int arr[10000];
int i = 0;
while (n) {
arr[i] = n % 26;
n = n / 26;
i++;
}
for (int j = 0; j < i - 1; j++) {
if (arr[j] <= 0) {
arr[j] += 26;
arr[j + 1] = arr[j + 1] - 1;
}
}
for (int j = i; j >= 0; j--) {
if (arr[j] > 0)
cout << char('A' + arr[j] - 1);
}
cout << endl;
}
int main()
{
printString(26);
printString(51);
printString(52);
printString(80);
printString(676);
printString(702);
printString(705);
return 0;
}
|
Java
import java.util.*;
class GFG{
static void printString(int n)
{
int []arr = new int[10000];
int i = 0;
while (n > 0)
{
arr[i] = n % 26;
n = n / 26;
i++;
}
for(int j = 0; j < i - 1; j++)
{
if (arr[j] <= 0)
{
arr[j] += 26;
arr[j + 1] = arr[j + 1] - 1;
}
}
for(int j = i; j >= 0; j--)
{
if (arr[j] > 0)
System.out.print(
(char)('A' + arr[j] - 1));
}
System.out.println();
}
public static void main(String[] args)
{
printString(26);
printString(51);
printString(52);
printString(80);
printString(676);
printString(702);
printString(705);
}
}
|
Python3
def printString(n):
arr = [0] * 10000
i = 0
while (n > 0):
arr[i] = n % 26
n = int(n // 26)
i += 1
for j in range(0, i - 1):
if (arr[j] <= 0):
arr[j] += 26
arr[j + 1] = arr[j + 1] - 1
for j in range(i, -1, -1):
if (arr[j] > 0):
print(chr(ord('A') +
(arr[j] - 1)), end = "");
print();
if __name__ == '__main__':
printString(26);
printString(51);
printString(52);
printString(80);
printString(676);
printString(702);
printString(705);
|
C#
using System;
class GFG{
static void printString(int n)
{
int []arr = new int[10000];
int i = 0;
while (n > 0)
{
arr[i] = n % 26;
n = n / 26;
i++;
}
for(int j = 0; j < i - 1; j++)
{
if (arr[j] <= 0)
{
arr[j] += 26;
arr[j + 1] = arr[j + 1] - 1;
}
}
for(int j = i; j >= 0; j--)
{
if (arr[j] > 0)
Console.Write((char)('A' +
arr[j] - 1));
}
Console.WriteLine();
}
public static void Main(String[] args)
{
printString(26);
printString(51);
printString(52);
printString(80);
printString(676);
printString(702);
printString(705);
}
}
|
Javascript
<script>
function printString(n){
let arr = [];
let i = 0;
while (n) {
arr[i] = n % 26;
n = Math.floor(n / 26);
i++;
}
for (let j = 0; j < i - 1; j++) {
if (arr[j] <= 0) {
arr[j] += 26;
arr[j + 1] = arr[j + 1] - 1;
}
}
let ans = '';
for (let j = i; j >= 0; j--) {
if (arr[j] > 0)
ans += String.fromCharCode(65 + arr[j] - 1);
}
document.write(ans + "<br>");
}
printString(26);
printString(51);
printString(52);
printString(80);
printString(676);
printString(702);
printString(705);
</script>
|
Output
Z
AY
AZ
CB
YZ
ZZ
AAC
Time Complexity: O(log26n), as we are using a loop and in each traversal, we decrement by floor division of 26.
Auxiliary Space: O(10000), as we are using extra space for the array.
Method 3:
We can use a recursive function which definitely reduces the time and increase the efficiency:
Alphabets are in sequential order like: ‘ABCDEFGHIJKLMNOPQRSTUVWXYZ’. You have experienced while using excel when you see columns and rows numbering are done in Alphabetical ways.
Here’s How I purposefully think about the logic of how it is arranged.
(In Mathematical terms, [a , b ] means from ‘a’ to ‘b’).
[1,26] = [A,Z] (Understand by ‘1’ stands for ‘A’ and ’26” stands for “Z”). For [27,52] ,it will be like [AA,AZ], For [57,78] it will be [BA,BZ]
Logic is to append an Alphabet sequentially whenever it ends up numbering at 26.
For example, if the number is ’27’ which is greater than ’26’, then we simply need to divide by 26, and we get the remainder as 1, We see “1” as “A” and can be recursively done.
we will be using python for this.
Algorithm is:
1. Take an array and Sort the letters from A to Z . (You can also use the import string and string function to get “A to Z” in uppercase.)
2. If the number is less than or equal to ’26’, simply get the letter from the array and print it.
3. If it is greater than 26, use the Quotient Remainder rule, if the remainder is zero, there are 2 possible ways, if the quotient is “1”, simply hash out the letter from the index [r-1]( ‘r’ is remainder), else call out the function from the num =(q-1) and append at the front to the letter indexing [r-1].
4. If the remainder is not equal to “0”, call the function for the num = (q) and append at the front to the letter indexing [r-1].
The code concerned with this is:
C++
#include<bits/stdc++.h>
using namespace std;
string alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
string num_hash(int num){
if(num < 26){
string res = "";
res += alpha[num-1];
return res;
}
else{
int q = (num / 26);
int r = num % 26;
string res = "";
if(r == 0){
if(q == 1){
res.append(1,alpha[(26 + r-1)%26]);
}
else{
res = num_hash(q-1);
res.append(1,alpha[(26 + r-1)%26]);
}
}
else{
res = num_hash(q);
res.append(1,alpha[(26 + r-1)%26]);
}
return res;
}
}
int main () {
cout<< num_hash(26) << endl;
cout<< num_hash(51) << endl;
cout<< num_hash(52) << endl;
cout<< num_hash(80) << endl;
cout<< num_hash(676) << endl;
cout<< num_hash(702) << endl;
cout<< num_hash(705) << endl;
return 0;
}
|
Java
import java.io.*;
class GFG
{
static String alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static String num_hash(int num){
if(num < 26)
return Character.toString(alpha.charAt(num-1));
else{
int q = Math.floorDiv(num, 26);
int r = num % 26;
if(r == 0){
if(q == 1){
return Character.toString(alpha.charAt((26 + r-1)%26));
}
else
return num_hash(q-1) + alpha.charAt((26 + r-1)%26);
}
else
return num_hash(q) + alpha.charAt((26 + r-1)%26);
}
}
public static void main (String[] args) {
System.out.println(num_hash(26));
System.out.println(num_hash(51));
System.out.println(num_hash(52));
System.out.println(num_hash(80));
System.out.println(num_hash(676));
System.out.println(num_hash(702));
System.out.println(num_hash(705));
}
}
|
Python3
alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def num_hash(num):
if num < 26:
return alpha[num-1]
else:
q, r = num//26, num % 26
if r == 0:
if q == 1:
return alpha[r-1]
else:
return num_hash(q-1) + alpha[r-1]
else:
return num_hash(q) + alpha[r-1]
print(num_hash(26))
print(num_hash(51))
print(num_hash(52))
print(num_hash(80))
print(num_hash(676))
print(num_hash(702))
print(num_hash(705))
|
C#
using System;
class GFG
{
static string alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static string num_hash(int num){
if(num < 26)
return Char.ToString(alpha[num-1]);
else{
int q = num/26;
int r = num % 26;
if(r == 0){
if(q == 1){
return Char.ToString(alpha[(26 + r-1)%26]);
}
else
return num_hash(q-1) + alpha[(26 + r-1)%26];
}
else
return num_hash(q) + alpha[(26 + r-1)%26];
}
}
public static void Main(String[] args) {
Console.WriteLine(num_hash(26));
Console.WriteLine(num_hash(51));
Console.WriteLine(num_hash(52));
Console.WriteLine(num_hash(80));
Console.WriteLine(num_hash(676));
Console.WriteLine(num_hash(702));
Console.WriteLine(num_hash(705));
}
}
|
Javascript
<script>
let alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
function num_hash(num)
{
if(num < 26)
return alpha[num-1]
else{
let q = Math.floor(num/26),r = num % 26
if(r == 0){
if(q == 1)
return alpha[(26 + r-1)]
else
return num_hash(q-1) + alpha[(26 + r-1)]
}
else
return num_hash(q) + alpha[r-1]
}
}
document.write(num_hash(26),"</br>")
document.write(num_hash(51),"</br>")
document.write(num_hash(52),"</br>")
document.write(num_hash(80),"</br>")
document.write(num_hash(676),"</br>")
document.write(num_hash(702),"</br>")
document.write(num_hash(705),"</br>")
</script>
|
Output
Z
AY
AZ
CB
YZ
ZZ
AAC
Time Complexity: O(log26n), as we are using recursion and in each recursive call, we decrement by floor division of 26.
Auxiliary Space: O(1), as we are not using any extra space.
Related Article :
Find the Excel column number from the column title
Similar Reads
Find Excel column name from a given column number
MS Excel columns have a pattern like A, B, C, …, Z, AA, AB, AC, …., AZ, BA, BB, … ZZ, AAA, AAB ..... etc. In other words, column 1 is named "A", column 2 as "B", and column 27 as "AA".Given a column number, find its corresponding Excel column name. The following are more examples. Input Output 26 Z
15+ min read
Find Excel column number from column title
We have discussed Conversion from column number to Excel Column name. In this post, reverse is discussed. Given a column title as appears in an Excel sheet, return its corresponding column number. column column number A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 Examples: Inp
4 min read
Find maximum element of each column in a matrix
Given a matrix, the task is to find the maximum element of each column. Examples: Input: [1, 2, 3] [1, 4, 9] [76, 34, 21] Output: 76 34 21 Input: [1, 2, 3, 21] [12, 1, 65, 9] 1, 56, 34, 2] Output: 12 56 65 21 Approach: The idea is to run the loop for no_of_cols. Check each element inside the column
6 min read
Find N in the given matrix that follows a pattern
Given an infinite matrix filled with the natural numbers as shown below: 1 2 4 7 . . . 3 5 8 . . . . 6 9 . . . . . 10 . . . . . . . . . . . . Also, given an integer N and the task is to find the row and the column of the integer N in the given matrix.Examples: Input: N = 5 Output: 2 2 5 is present i
8 min read
Sum of digits equal to a given number in PL/SQL
Prerequisite - PL/SQL introduction In PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations. Given a number and range and the task is to display all
2 min read
Program to find all types of Matrix
Given the dimension of the matrix R(rows) * C(column) the task is to find which type of matrix is represented by the given dimension. Examples: Input : R = 1 C = 0Output : Row Matrix Input : R = 4 C = 5Output : Horizontal Matrix Row Matrix : When R = 1 and C = 0 then the matrix represent Row Matrix
5 min read
Columnar Transposition Cipher
Given a plain-text message and a numeric key, cipher/de-cipher the given text using Columnar Transposition Cipher The Columnar Transposition Cipher is a form of transposition cipher just like Rail Fence Cipher. Columnar Transposition involves writing the plaintext out in rows, and then reading the c
12 min read
Select DataFrame Column Using Character Vector in R
In this article, we will discuss how to select dataframe columns using character vectors in R programming language. Data frame in use: To extract columns using character we have to use colnames() function and the index of the column to select is given with it using []. The approach is sort of the sa
2 min read
How to Get Column Names in Pandas Dataframe
While analyzing the real datasets which are often very huge in size, we might need to get the pandas column names in order to perform some certain operations. The simplest way to get column names in Pandas is by using the .columns attribute of a DataFrame. Let's understand with a quick example: [GFG
4 min read
SQL Query to Get Column Names From a Table
SQL stands for Structured Query Language. It is a language used to interact with the database, i.e to create a database, to create a table in the database, to retrieve data or update a table in the database, etc. SQL is an ANSI(American National Standards Institute) standard. Using SQL, we can do ma
2 min read
How to Retrieve Row Numbers in R DataFrame?
In this article, we will discuss how to Retrieve Row Numbers in R Programming Language. The dataframe column can be referenced using the $ symbol, which finds its usage as data-frame$col-name. The which() method is then used to retrieve the row number corresponding to the true condition of the speci
2 min read
Change more than one column name of a given DataFrame in R
A data frame is a tabular structure with fixed dimensions, of each row as well as columns. It is a two-dimensional array-like object with numerical, character-based, or factor-type data. Each element belonging to the data frame is indexed by a unique combination of the row and column number respecti
4 min read
How to Loop Through Column Names in R dataframes?
In this article, we will discuss how to loop through column names in dataframe in R Programming Language. Method 1: Using sapply() Here we are using sapply() function with some functions to get column names. This function will return column names with some results Syntax: sapply(dataframe,specific f
2 min read
How to select multiple DataFrame columns by name in R ?
In this article, we will discuss how to select multiple columns from a DataFrame by name in R Programming Language. To get multiple columns we will use the list data structure. By using a list we can pass the dataframe columns separated with a comma. Then, we can get list by using list() function Sy
1 min read
How to get name of dataframe column in PySpark ?
In this article, we will discuss how to get the name of the Dataframe column in PySpark. To get the name of the columns present in the Dataframe we are using the columns function through this function we will get the list of all the column names present in the Dataframe. Syntax: df.columns We can al
3 min read
How to get column and row names in DataFrame?
While analyzing the real datasets which are often very huge in size, we might need to get the rows or index names and columns names in order to perform certain operations. Note: For downloading the nba dataset used in the below examples Click Here Getting row names in Pandas dataframe First, let's c
3 min read
Get column index from column name of a given Pandas DataFrame
Let's learn how to get the index of a column based on its name using the DataFrame.columns attribute and Index.get_loc() method from the pandas library. Index.get_loc() Method Index.get_loc() function finds the index of a specified column name and returns an integer if the column name is unique. Syn
2 min read
Create empty DataFrame with only column names in R
In this article, we are going to discuss how to create a data frame in r with column names and create an empty data frame with column names in the R Programming Language. The basic syntax for creating a data frame is using data. frame(). Create a Data Frame with Values and column Names C/C++ Code #
3 min read
Naming Rows and Columns of a Matrix in R Programming - rownames() and colnames() Function
rownames() function in R Language is used to set the names to rows of a matrix. Syntax: rownames(x) <- value Parameters: x: Matrix value: Vector of names to be set Example: # R program to provide a name # to rows of a Matrix # Creating a 3X3 Matrix A = matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9), 3, 3, b
1 min read
Get values of all rows in a particular column in openpyxl - Python
In this article, we will explore how to get the values of all rows in a particular column in a spreadsheet using openpyxl in Python. We will start by discussing the basics of openpyxl and how to install and import it. Then, we will walk through for example, how to extract the values of a particular
4 min read