如何使用 Java return 具有 'Excel style' 列标题的字符串?
How to return a String that has 'Excel style' column headings using Java?
我一直在尝试弄清楚如何 return 以这样的方式格式化字符串(例如):
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())
我的问题是关于字符串顶部的列号;我正在尝试根据该数字在字母表中的位置(显然从零开始),以每个列号以字母表中的字母为前缀的方式对它们进行格式化。
在问题标题中我说:"Excel style"。基本上,如果您查看 excel,您会注意到这些列实际上是字母表中的字母,只要电子表格继续,它就会继续,当字母表到达 'Z' 时,它会继续通过将另一个字母添加到字母表的第一个字母,即 'AA' 等等,实际上为每一列提供了一个唯一的名称..
然而,在我的例子中,我需要在列的编号前加上相同的样式,并且该编号也用方括号括起来,直到电子表格中有一个条目的最大列。
我相信使这项工作肯定与模块化算法有关,但不确定如何去做。
这是我写的东西:
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;
}
这是输出(本质上)的内容:
(0) (1) (2) (3) (4) -> (to maxColumn())
我刚刚开始研究如何让这些数字以字母表为前缀。
非常感谢任何想法或帮助!
我用这种方法运行 进行了一些测试,它似乎有效,并且适用于任何大于 1 的整数列号。您可以自己 运行 进行更广泛的测试。
/**
* 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();
}
我一直在尝试弄清楚如何 return 以这样的方式格式化字符串(例如):
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())
我的问题是关于字符串顶部的列号;我正在尝试根据该数字在字母表中的位置(显然从零开始),以每个列号以字母表中的字母为前缀的方式对它们进行格式化。
在问题标题中我说:"Excel style"。基本上,如果您查看 excel,您会注意到这些列实际上是字母表中的字母,只要电子表格继续,它就会继续,当字母表到达 'Z' 时,它会继续通过将另一个字母添加到字母表的第一个字母,即 'AA' 等等,实际上为每一列提供了一个唯一的名称..
然而,在我的例子中,我需要在列的编号前加上相同的样式,并且该编号也用方括号括起来,直到电子表格中有一个条目的最大列。
我相信使这项工作肯定与模块化算法有关,但不确定如何去做。
这是我写的东西:
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;
}
这是输出(本质上)的内容:
(0) (1) (2) (3) (4) -> (to maxColumn())
我刚刚开始研究如何让这些数字以字母表为前缀。
非常感谢任何想法或帮助!
我用这种方法运行 进行了一些测试,它似乎有效,并且适用于任何大于 1 的整数列号。您可以自己 运行 进行更广泛的测试。
/**
* 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();
}