How to convert spreadsheet column number to label?

There are a couple of ways to approach the problem of converting a spreadsheet column number to a spreadsheet style label. The following shows how our column numbers need to be mapped:

0 -> A
1 -> B
2 -> C

25 -> Z
26 -> AA
27 -> AB

Firstly using recursion:

public static String getColumnLabel(int columnNumber) {
	char c = (char) ('A' + (columnNumber % 26));
    if (columnNumber<26) {
     return Character.toString(c);
   } else {
     return getColumnLabel(columnNumber/ 26 - 1)+c;
   }
}

And secondly using a loop instead of recursion:

public static String getColumnLabel(int columnNumber) {
    StringBuilder result = new StringBuilder();
    for (; columnNumber >= 0; columnNumber = columnNumber / 26 - 1) {
        result.insert(0, (char)(columnNumber % 26 +'A'));
    }
    return result.toString();
}

你可能感兴趣的:(How to convert spreadsheet column number to label?)