Excel 单元格地址有两种格式:
普通格式,如:A5, BC12
对应的RC格式:R5C1, R12C55
显然,RC格式是直接给出行号和列号
请编程在两种地址格式间转换。
public class A
{
static String A1toRC(String x)
{
String x1 = ""; //列部分
String x2 = ""; //行部分
for(int i=0; i<x.length(); i++){
char c = x.charAt(i);
if(c>='0' && c <='9'){
x1 = x.substring(0,i);
x2 = x.substring(i);
break;
}
}
if(x1.length()==1)
return "R" + x2 + "C" + (x1.charAt(0) - 'A' + 1);
else
return "R" + x2 + "C"
+ ((x1.charAt(0)-'A') * 26 + (x1.charAt(1)-'A') + 27);
}
public static void main(String[] args)
{
System.out.println(A1toRC("Z5"));
System.out.println(A1toRC("BC5"));
}
}
上面是标准答案。。但只有A1toRC 的转化代码。。下面提供2种格式互转的代码
package lianxijihe;
public class lianxi033 {
public static void main(String[] args) {
A("BC5");
B("R12C55");
}
public static void A(String a) {//A5转成R5C1的方法
int x = 0;
int y = 0;
for (int i = 0; i < a.length(); i++) {
char s = a.charAt(i);
if ((s - 'A' + 1) <= 0) { //如果不是字母
y = y * 10 + (s - '0');//则存入Y中。是10进制
} else {
x = x * 26 + (s - 'A' + 1);//如果是字母则存入X中。把26进制转换成10进制
}
}
System.out.println("R" + y + "C" + x);
}
public static void B(String b){//R5C1转A5的方法
String x ; //用来存行号
String y = "" ;//用来存列号
x = b.substring(1, b.indexOf('C'));//把R到C的所有数字存到行号里
int t = Integer.parseInt(b.substring(b.indexOf('C')+1));//把列号转换成整形
while(t>0){ //把T转换成26进制。0-25用A-Z表示
y= (char)((t%26)+'A'-1)+y;
t=t/26;
}
System.out.println(y+x);
}
}