Excel 列号数字与字母互相转换-JAVA实现

已剪辑自: https://blog.csdn.net/u010571844/article/details/46806265

我们在实现对Excel的导入导出的时候,往往需要准确的给用户提示信息,提示到具体的Excel的单元格,这里就需要对Excel的列号进行数字和字母的转换,今天正好用到这个需求,所以就写了一个demo,总结一下:

Java实现

public class ExcelColumn {

public static void main(String[] args) {
String colstr = “AA”;
int colIndex = excelColStrToNum(colstr, colstr.length());
System.out.println(“‘” + colstr + “‘ column index of ” + colIndex);

colIndex = 26;
colstr = excelColIndexToStr(colIndex);
System.out.println(colIndex + ” column in excel of ” + colstr);

colstr = “AAAA”;
colIndex = excelColStrToNum(colstr, colstr.length());
System.out.println(“‘” + colstr + “‘ column index of ” + colIndex);

colIndex = 466948;
colstr = excelColIndexToStr(colIndex);
System.out.println(colIndex + ” column in excel of ” + colstr);
}

public static int excelColStrToNum(String colStr, int length) {
int num = 0;
int result = 0;
for(int i = 0; i < length; i++) {
char ch = colStr.charAt(length – i – 1);
num = (int)(ch – ‘A’ + 1) ;
num *= Math.pow(26, i);
result += num;
}
return result;
}

public static String excelColIndexToStr(int columnIndex) {
if (columnIndex <= 0) {
return null;
}
String columnStr = “”;
columnIndex–;
do {
if (columnStr.length() > 0) {
columnIndex–;
}
columnStr = ((char) (columnIndex % 26 + (int) ‘A’)) + columnStr;
columnIndex = (int) ((columnIndex – columnIndex % 26) / 26);
} while (columnIndex > 0);
return columnStr;
}
}

测试结果:

AA column index of 27
26 column in excel of Z
AAAA column index of 18279
466948 column in excel of ZNSN



打赏

发表评论

电子邮件地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据