Java : Excel Cell名->Apache POI Cell位置変換処理
概要
Apache POIでのExcelセル指定は0~の数字。
実際のExcel上ではA~の英字。ZまでいくとAA、ZZまでいくとAAAとなる。
プログラミング上でもExcel上の表記と合わせたいと考え作成。
コード
/**
* Excel Cell名->POI Cell位置変換処理
* @param cellString Excel Cell名(A-)
* @return POI Cell位置(0-) -1 : 異常時
*/
static public int changeCellNo(String cellString) {
int cellNo = -1;
String reg = "^[A-Z]+$";
Matcher matcher = Pattern.compile(reg).matcher(cellString);
if(matcher.find() == true) {
char[] cellChars = cellString.toCharArray();
for(int i = cellChars.length - 1, j = 0; i >= 0; i--, j++) {
cellNo += ((int)cellChars[i] - 65 + 1) * (j == 0 ? 1 : (int)Math.pow(26, j));
}
}
return cellNo;
}
memo
旧ブログ記事2014年1月14日の再掲載。



