Java jxl api v2.6.16 を使用して Excel スプレッドシートを生成しています。上記のタイトルのように、セルの列と行しかない場合、書き込み中のセルまたはより具体的には書き込み可能なセルのアドレスを取得するにはどうすればよいですか? または、それを生成できるアルゴリズムを作成する必要がありますか?
前もって感謝します。
このコードを使用できます。この助けを願っています。次のように使用できます。
cellAddress(cell.getRow() + 1, cell.getColumn())
セルが次のように定義されている場合Cell cell = someCell;
private String cellAddress(Integer rowNumber, Integer colNumber){
return "$"+columnName(colNumber)+"$"+rowNumber;
}
private String columName(Integer colNumber) {
Base columns = new Base(colNumber,26);
columns.transform();
return columns.getResult();
}
class Base {
String[] colNames = "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z".split(",");
String equalTo;
int position;
int number;
int base;
int[] digits;
int[] auxiliar;
public Base(int n, int b) {
position = 0;
equalTo = "";
base = b;
number = n;
digits = new int[1];
}
public void transform() {
if (number < base) {
digits[position] = number;
size();
} else {
digits[position] = number % base;
size();
position++;
number = number / base;
transform();
}
}
public String getResult() {
for (int j = digits.length - 2; j >= 0; j--) {
equalTo += colNames[j>0?digits[j]-1:digits[j]];
}
return equalTo;
}
private void size() {
auxiliar = digits;
digits = new int[auxiliar.length + 1];
System.arraycopy(auxiliar, 0, digits, 0, auxiliar.length);
}
}
以下のいずれかの方法を使用して、アルファ インデックスで列を取得できます。簡単な方法は、整数を ASCII 文字にキャストするだけです。2 番目の方法では、カスタム アルファベットを使用できます。
public class LookupUtil {
public static String cellAddress(int row, int col) {
return String.format("$%s$%d", columnName(col), row);
}
public static String columnName(int index) {
int div = index + 1;
StringBuffer result = new StringBuffer();
int mod = 0;
while (div > 0) {
mod = (div - 1) % 26;
result.insert(0, (char) (65 + mod));
div = (int) ((div - mod) / 26);
}
return result.toString();
}
}
public class LookupUtil {
private static final char[] ALPHA = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
public static String cellAddress(int row, int col) {
return String.format("$%s$%d", columnName(col, ALPHA), row);
}
public static String columnName(int index, char[] alphabet) {
int div = index + 1;
StringBuffer result = new StringBuffer();
int mod = 0;
while (div > 0) {
mod = (div - 1) % alphabet.length;
result.insert(0, alphabet[mod]);
div = (int) ((div - mod) / alphabet.length);
}
return result.toString();
}
}
アドレスは列と行で構成されています。
A1 記法では、次のように記述されRange("A1")
ます。列 1 は文字「A」で表され、行は 1 です。
R1C1 記法では、次のように記述されます。R1C1
列が 1 で行が 1 の場合
それらは次のように使用されます。
Cells(1,1).font.bold=true ' row 1, column 1
range("A1").font.bold=true
Reference からアドレスを取得するには、次のようにCellsまたはRangeオブジェクトのAddressプロパティを取得します。
sAddress=cells(1,1).address
これはA$1$を返します
JXLでは、String rangeAddress = range.getAddress();