I've been trying to figure out how to return a String formatted in such a way that it looks like this (for example):
A(0) B(1) C(2) -> Z(25) -> AC(28) -> (to maxColumn()).
0 - - 1.2 - -
1 1.0 - - 8.8 6.1
3 - - - - 0.1
(to maxRow())
My question here is in regards to the column numbers at the top of the string; I'm trying to format them in such a way that each column number is prefixed by a letter of the alphabet, according to that number's position in the alphabet (obviously starting from zero).
In the question title I say: "Excel style". Basically, if you take a look in excel you'll notice that the columns are in facts letters of the alphabet that continue for as long as the spreadsheet goes, and when the alphabet reaches 'Z', it continues by adding another letter to the first letter of the alphabet, i.e. 'AA' and so on, in effect giving each column a unique name..
In my case however, I need to have that same style prefixing the column's number, and that number also being enclosed with brackets, until the maximum column for which there is an entry in the spreadsheet.
I believe that making this work definitely has something to do with modular arithmetic, not sure how to go about that though.
Here's something that I wrote:
public String toString() { //overrides toString() in Object for the purposes of this implementation.
String columns = "";
for (int i = 0; i < maxColumn(); i++) {
columns += "(" + i + ")" + "\t";
}
return columns;
}
and here is what that outputs (essentially):
(0) (1) (2) (3) (4) -> (to maxColumn())
I'm just after a bit of a kick start for working out how to get these numbers prefixed with the alphabet.
Any ideas or help is much appreciated!
I ran a few tests with this method, it seems to work, and it will work for any integer column number greater than 1. You can run more extensive tests on your own.
/**
* Convert an Excel-style column index to an Excel-style column name.
* @param colIndex first index = 1, per Excel standard
* @return Excel-style column name
*/
public String toExcelHeaderName(int colIndex) {
StringBuilder sb = new StringBuilder();
int div = colIndex;
do {
div = div - 1;
int remainder = div % 26;
char colLetter = (char) ('A' + remainder);
sb.insert(0, colLetter);
div = (div / 26);
} while (div > 0);
return sb.toString();
}