Bipo K
Bipo K

Reputation: 393

Google Sheet API V4 Java, Get Column Letter from Column Number

Hello: Using Google Spreadsheet API V4 on Java, I want to to get the column letter given the column number. Example: the column letter for column number 2 is B.

Is there some way already provisioned in Google spreadsheet API OR is there any other simple way to go do this OR do i need to write my own conversion?

Upvotes: 3

Views: 2908

Answers (2)

albrnick
albrnick

Reputation: 1241

I think you could also just use the R1C1 notation mentioned here:

https://developers.google.com/sheets/api/guides/concepts

This let's you use column numbers instead of letters.

Upvotes: 4

Bipo K
Bipo K

Reputation: 393

Though the Question still is: Is there a native way in Google Spreadsheet API V4 to get the column letter given the column number?

However, for future reference i am providing below a collation in case someone needs to implement his own conversion.

Case 1: Get Column Letter Given the Column Number

public void ColumnNumberToLetter() {
    int inputColumnNumber = 49;
    String outputColumnName = "";
    int Base = 26;        
    String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";        

    int TempNumber = inputColumnNumber;
    while (TempNumber > 0) {
       int position = TempNumber % Base;
       outputColumnName = (position == 0 ? 'Z' : chars.charAt(position > 0 ? position - 1 : 0)) + outputColumnName;
       TempNumber = (TempNumber - 1) / Base;
    }
    System.out.println("ColumnNumberToLetter :" + inputColumnNumber + " = " +  outputColumnName);
}

Case 2: Get Column Number Given the Column Letter

public void ColumnLetterToNumber() {
    String inputColumnName = "AW";
    int outputColumnNumber = 0;

    if (inputColumnName == null || inputColumnName.length() == 0) {
        throw new IllegalArgumentException("Input is not valid!");
    }

    int i = inputColumnName.length() - 1;
    int t = 0;
    while (i >= 0) {
        char curr = inputColumnName.charAt(i);
        outputColumnNumber = outputColumnNumber + (int) Math.pow(26, t) * (curr - 'A' + 1);
        t++;
        i--;
    }
    System.out.println("ColumnLetterToNumber : " + inputColumnName + " = " +  outputColumnNumber);
}

Upvotes: 4

Related Questions